-
+
@@ -16,6 +16,8 @@
+
+
@@ -359,6 +361,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
@@ -409,7 +423,6 @@
-
@@ -420,24 +433,25 @@
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Mac/MainMenu/mul.lproj/MainMenu.xcstrings b/Mac/MainMenu/mul.lproj/MainMenu.xcstrings
index 6e06ae635..19eda08b0 100644
--- a/Mac/MainMenu/mul.lproj/MainMenu.xcstrings
+++ b/Mac/MainMenu/mul.lproj/MainMenu.xcstrings
@@ -1963,6 +1963,30 @@
}
}
},
+ "stB-ar-mI1.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Show Status Bar\"; ObjectID = \"stB-ar-mI1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Show Status Bar"
+ }
+ }
+ }
+ },
+ "stT-hm-mI1.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Show Theme Menu in Status Bar\"; ObjectID = \"stT-hm-mI1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Show Theme Menu in Status Bar"
+ }
+ }
+ }
+ },
"Td7-aD-5lo.title" : {
"comment" : "Class = \"NSMenu\"; title = \"Window\"; ObjectID = \"Td7-aD-5lo\";",
"extractionState" : "extracted_with_value",
diff --git a/Mac/MainWindow/AddFolder/AddFolderWindowController.swift b/Mac/MainWindow/AddFolder/AddFolderWindowController.swift
index 0e9c1626d..c6c1be926 100644
--- a/Mac/MainWindow/AddFolder/AddFolderWindowController.swift
+++ b/Mac/MainWindow/AddFolder/AddFolderWindowController.swift
@@ -40,7 +40,7 @@ final class AddFolderWindowController: NSWindowController {
// MARK: - NSViewController
override func windowDidLoad() {
- let preferredAccountID = AppDefaults.shared.addFolderAccountID
+ let preferredAccountID = AppDefaults.addFolderAccountID
accountPopupButton.removeAllItems()
let menu = NSMenu()
@@ -104,7 +104,7 @@ private extension AddFolderWindowController {
}
let account = menuItem.representedObject as! Account
- AppDefaults.shared.addFolderAccountID = account.accountID
+ AppDefaults.addFolderAccountID = account.accountID
let folderName = self.folderNameTextField.stringValue
if folderName.isEmpty {
diff --git a/Mac/MainWindow/ArticleThemesManager+Menu.swift b/Mac/MainWindow/ArticleThemesManager+Menu.swift
new file mode 100644
index 000000000..46ec73f9a
--- /dev/null
+++ b/Mac/MainWindow/ArticleThemesManager+Menu.swift
@@ -0,0 +1,33 @@
+//
+// ArticleThemesManager+Menu.swift
+// NetNewsWire
+//
+// Created by Brent Simmons on 10/13/26.
+// Copyright © 2026 Ranchero Software. All rights reserved.
+//
+
+import AppKit
+
+extension ArticleThemesManager {
+
+ /// The default theme, a separator, then the other themes. The current theme is checked.
+ @MainActor func makeArticleThemeMenu() -> NSMenu {
+ let articleThemeMenu = NSMenu()
+
+ func addThemeItem(_ themeName: String) {
+ let themeItem = NSMenuItem()
+ themeItem.title = themeName
+ themeItem.action = #selector(MainWindowController.selectArticleTheme(_:))
+ themeItem.state = themeName == currentThemeName ? .on : .off
+ articleThemeMenu.addItem(themeItem)
+ }
+
+ addThemeItem(ArticleTheme.defaultTheme.name)
+ articleThemeMenu.addItem(NSMenuItem.separator())
+ for themeName in themeNames {
+ addThemeItem(themeName)
+ }
+
+ return articleThemeMenu
+ }
+}
diff --git a/Mac/MainWindow/ColumnLayoutSplitView.swift b/Mac/MainWindow/ColumnLayoutSplitView.swift
index 6be6f87cf..e8e0346a8 100644
--- a/Mac/MainWindow/ColumnLayoutSplitView.swift
+++ b/Mac/MainWindow/ColumnLayoutSplitView.swift
@@ -10,7 +10,7 @@ import AppKit
/// The split between the timeline and the article view in column layout.
/// On macOS 26 it extends under the sidebar, so the divider is drawn in the visible part only — otherwise the dimple is off-center.
-final class ColumnLayoutSplitView: NSSplitView {
+final class ColumnLayoutSplitView: MainWindowSplitView {
override func drawDivider(in rect: NSRect) {
super.drawDivider(in: rect.intersection(safeAreaRect))
diff --git a/Mac/MainWindow/Detail/Base.lproj/DetailView.xib b/Mac/MainWindow/Detail/Base.lproj/DetailView.xib
index ccacb0c80..4057af57c 100644
--- a/Mac/MainWindow/Detail/Base.lproj/DetailView.xib
+++ b/Mac/MainWindow/Detail/Base.lproj/DetailView.xib
@@ -8,7 +8,7 @@
-
+
@@ -18,7 +18,7 @@
-
+
@@ -48,7 +48,7 @@
-
+
diff --git a/Mac/MainWindow/Detail/DetailContainerView.swift b/Mac/MainWindow/Detail/DetailContainerView.swift
index 468666f8d..32b5de723 100644
--- a/Mac/MainWindow/Detail/DetailContainerView.swift
+++ b/Mac/MainWindow/Detail/DetailContainerView.swift
@@ -10,7 +10,7 @@ import AppKit
final class DetailContainerView: NSView {
- @IBOutlet var detailStatusBarView: DetailStatusBarView!
+ @IBOutlet var linkOverlayView: DetailLinkOverlayView!
var contentViewConstraints: [NSLayoutConstraint]?
@@ -28,7 +28,7 @@ final class DetailContainerView: NSView {
if let contentView = contentView {
contentView.translatesAutoresizingMaskIntoConstraints = false
- addSubview(contentView, positioned: .below, relativeTo: detailStatusBarView)
+ addSubview(contentView, positioned: .below, relativeTo: linkOverlayView)
// Leading and trailing follow the safe area so the article view doesn’t extend under the sidebar
// in column layout on macOS 26. Top stays at the edge: the web view handles the toolbar itself.
let constraints = [
diff --git a/Mac/MainWindow/Detail/DetailIconSchemeHandler.swift b/Mac/MainWindow/Detail/DetailIconSchemeHandler.swift
index 2bb7ed356..9b18aa1f5 100644
--- a/Mac/MainWindow/Detail/DetailIconSchemeHandler.swift
+++ b/Mac/MainWindow/Detail/DetailIconSchemeHandler.swift
@@ -16,7 +16,7 @@ final class DetailIconSchemeHandler: NSObject, WKURLSchemeHandler {
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
- guard let responseURL = urlSchemeTask.request.url, let iconImage = self.currentArticle?.iconImage() else {
+ guard let responseURL = urlSchemeTask.request.url, let iconImage = self.currentArticle?.articleViewIconImage() else {
urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist))
return
}
@@ -31,16 +31,17 @@ final class DetailIconSchemeHandler: NSObject, WKURLSchemeHandler {
}
let headerFields = ["Cache-Control": "no-cache"]
- if let response = HTTPURLResponse(url: responseURL, statusCode: 200, httpVersion: nil, headerFields: headerFields) {
- urlSchemeTask.didReceive(response)
- urlSchemeTask.didReceive(data)
- urlSchemeTask.didFinish()
+ guard let response = HTTPURLResponse(url: responseURL, statusCode: 200, httpVersion: nil, headerFields: headerFields) else {
+ urlSchemeTask.didFailWithError(URLError(.unknown))
+ return
}
-
+ urlSchemeTask.didReceive(response)
+ urlSchemeTask.didReceive(data)
+ urlSchemeTask.didFinish()
}
+ /// Every task finishes in `start`, and WebKit raises an exception for any call on a stopped task.
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
- urlSchemeTask.didFailWithError(URLError(.unknown))
}
}
diff --git a/Mac/MainWindow/Detail/DetailStatusBarView.swift b/Mac/MainWindow/Detail/DetailLinkOverlayView.swift
similarity index 87%
rename from Mac/MainWindow/Detail/DetailStatusBarView.swift
rename to Mac/MainWindow/Detail/DetailLinkOverlayView.swift
index 16fcaed89..d1ff41378 100644
--- a/Mac/MainWindow/Detail/DetailStatusBarView.swift
+++ b/Mac/MainWindow/Detail/DetailLinkOverlayView.swift
@@ -1,5 +1,5 @@
//
-// DetailStatusBarView.swift
+// DetailLinkOverlayView.swift
// NetNewsWire
//
// Created by Brent Simmons on 12/16/17.
@@ -9,7 +9,7 @@
import AppKit
import Articles
-final class DetailStatusBarView: NSView {
+final class DetailLinkOverlayView: NSView {
@IBOutlet var urlLabel: NSTextField!
@@ -55,14 +55,14 @@ final class DetailStatusBarView: NSView {
didConfigureLayerRadius = true
}
- let color = self.effectiveAppearance.isDarkMode ? NSColor.textBackgroundColor : NSColor(named: "DetailStatusBarBackground")!
+ let color = self.effectiveAppearance.isDarkMode ? NSColor.textBackgroundColor : NSColor(named: "DetailLinkOverlayBackground")!
layer.backgroundColor = color.cgColor
}
}
// MARK: - Private
-private extension DetailStatusBarView {
+private extension DetailLinkOverlayView {
func updateLinkForDisplay() {
if let mouseoverLink = mouseoverLink, !mouseoverLink.isEmpty {
diff --git a/Mac/MainWindow/Detail/DetailViewController.swift b/Mac/MainWindow/Detail/DetailViewController.swift
index b81c2a3a1..072d41c57 100644
--- a/Mac/MainWindow/Detail/DetailViewController.swift
+++ b/Mac/MainWindow/Detail/DetailViewController.swift
@@ -20,10 +20,25 @@ enum DetailState: Equatable {
case extracted(Article, ExtractedArticle, CGFloat?)
}
+@MainActor protocol DetailViewControllerDelegate: AnyObject {
+ func detailViewController(_ detailViewController: DetailViewController, mouseoverLinkDidChange link: String?)
+}
+
final class DetailViewController: NSViewController, WKUIDelegate {
@IBOutlet var containerView: DetailContainerView!
- @IBOutlet var statusBarView: DetailStatusBarView!
+ @IBOutlet var linkOverlayView: DetailLinkOverlayView!
+
+ weak var delegate: DetailViewControllerDelegate?
+
+ /// Whether the hovered link shows in the floating overlay. The delegate gets the hovered link either way.
+ var showsMouseoverLinkOverlay = true {
+ didSet {
+ if showsMouseoverLinkOverlay != oldValue {
+ updateMouseoverLinkOverlay()
+ }
+ }
+ }
private lazy var regularWebViewController = createWebViewController()
private var searchWebViewController: DetailWebViewController?
@@ -38,11 +53,21 @@ final class DetailViewController: NSViewController, WKUIDelegate {
if containerView.contentView === webview {
return
}
- statusBarView.mouseoverLink = nil
+ mouseoverLink = nil
containerView.contentView = webview
}
}
+ private var mouseoverLink: String? {
+ didSet {
+ guard mouseoverLink != oldValue else {
+ return
+ }
+ updateMouseoverLinkOverlay()
+ delegate?.detailViewController(self, mouseoverLinkDidChange: mouseoverLink)
+ }
+ }
+
private var currentSourceMode: TimelineSourceMode = .regular {
didSet {
currentWebViewController = webViewController(for: currentSourceMode)
@@ -67,6 +92,7 @@ final class DetailViewController: NSViewController, WKUIDelegate {
override func viewDidLoad() {
currentWebViewController = regularWebViewController
+ updateMouseoverLinkOverlay()
}
// MARK: - API
@@ -126,14 +152,14 @@ extension DetailViewController: DetailWebViewControllerDelegate {
guard !link.isEmpty, detailWebViewController === currentWebViewController else {
return
}
- statusBarView.mouseoverLink = link
+ mouseoverLink = link
}
func mouseDidExit(_ detailWebViewController: DetailWebViewController) {
guard detailWebViewController === currentWebViewController else {
return
}
- statusBarView.mouseoverLink = nil
+ mouseoverLink = nil
}
}
@@ -141,6 +167,13 @@ extension DetailViewController: DetailWebViewControllerDelegate {
private extension DetailViewController {
+ func updateMouseoverLinkOverlay() {
+ guard isViewLoaded else {
+ return
+ }
+ linkOverlayView.mouseoverLink = showsMouseoverLinkOverlay ? mouseoverLink : nil
+ }
+
func createWebViewController() -> DetailWebViewController {
let controller = DetailWebViewController()
controller.delegate = self
diff --git a/Mac/MainWindow/Detail/DetailWebViewController.swift b/Mac/MainWindow/Detail/DetailWebViewController.swift
index 8c20ff318..0b5ddd793 100644
--- a/Mac/MainWindow/Detail/DetailWebViewController.swift
+++ b/Mac/MainWindow/Detail/DetailWebViewController.swift
@@ -54,8 +54,8 @@ final class DetailWebViewController: NSViewController {
}
}
- private var articleTextSize = AppDefaults.shared.articleTextSize
- private var isArticleContentJavascriptEnabled = AppDefaults.shared.isArticleContentJavascriptEnabled
+ private var articleTextSize = AppDefaults.articleTextSize
+ private var isArticleContentJavascriptEnabled = AppDefaults.isArticleContentJavascriptEnabled
private var webInspectorEnabled: Bool {
get {
@@ -116,9 +116,9 @@ final class DetailWebViewController: NSViewController {
NotificationCenter.default.addObserver(self, selector: #selector(webInspectorEnabledDidChange(_:)), name: .WebInspectorEnabledDidChange, object: nil)
- 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(handleFeedIconImageDidChange(_:)), name: .feedIconImageDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleGrayscaleIconsDidChange(_:)), name: .grayscaleIconsDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleAuthorAvatarImageDidChange(_:)), name: .authorAvatarImageDidChange, object: nil)
NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
Task { @MainActor in
self?.userDefaultsDidChange()
@@ -131,25 +131,25 @@ final class DetailWebViewController: NSViewController {
// MARK: Notifications
- @objc func feedIconDidBecomeAvailable(_ note: Notification) {
- reloadArticleImage()
+ @objc func handleFeedIconImageDidChange(_ notification: Notification) {
+ reloadArticleImageIfNeeded(notification)
}
- @objc func avatarDidBecomeAvailable(_ note: Notification) {
- reloadArticleImage()
+ @objc func handleAuthorAvatarImageDidChange(_ notification: Notification) {
+ reloadArticleImageIfNeeded(notification)
}
- @objc func faviconDidBecomeAvailable(_ note: Notification) {
+ @objc func handleGrayscaleIconsDidChange(_ notification: Notification) {
reloadArticleImage()
}
func userDefaultsDidChange() {
- if articleTextSize != AppDefaults.shared.articleTextSize {
- articleTextSize = AppDefaults.shared.articleTextSize
+ if articleTextSize != AppDefaults.articleTextSize {
+ articleTextSize = AppDefaults.articleTextSize
reloadHTMLMaintainingScrollPosition()
}
- if isArticleContentJavascriptEnabled != AppDefaults.shared.isArticleContentJavascriptEnabled {
- isArticleContentJavascriptEnabled = AppDefaults.shared.isArticleContentJavascriptEnabled
+ if isArticleContentJavascriptEnabled != AppDefaults.isArticleContentJavascriptEnabled {
+ isArticleContentJavascriptEnabled = AppDefaults.isArticleContentJavascriptEnabled
reloadHTMLMaintainingScrollPosition()
}
}
@@ -305,8 +305,18 @@ extension DetailWebViewController: WKNavigationDelegate, WKUIDelegate {
private extension DetailWebViewController {
+ /// Each reload draws and encodes the icon again, so icons for other feeds and authors are skipped.
+ func reloadArticleImageIfNeeded(_ notification: Notification) {
+ guard let article, article.mightShowIcon(in: notification) else {
+ return
+ }
+ reloadArticleImage()
+ }
+
func reloadArticleImage() {
- guard let article = article else { return }
+ guard let article else {
+ return
+ }
var components = URLComponents()
components.scheme = ArticleRenderer.imageIconScheme
@@ -329,7 +339,7 @@ private extension DetailWebViewController {
webView.navigationDelegate = self
webView.keyboardDelegate = keyboardDelegate
webView.autoresizingMask = [.width, .height]
- webView.configuration.preferences._developerExtrasEnabled = AppDefaults.shared.webInspectorEnabled
+ webView.configuration.preferences._developerExtrasEnabled = AppDefaults.webInspectorEnabled
return webView
}
@@ -369,6 +379,8 @@ private extension DetailWebViewController {
let theme = ArticleThemesManager.shared.currentTheme
let rendering: ArticleRenderer.Rendering
+ // Column layout shows no thumbnails, so there’s no timeline copy to share.
+ let routesThumbnailImages = AppDefaults.timelineLayout == .standard
switch state {
case .noSelection:
rendering = ArticleRenderer.noSelectionHTML(theme: theme)
@@ -378,10 +390,10 @@ private extension DetailWebViewController {
rendering = ArticleRenderer.loadingHTML(theme: theme)
case .article(let article, _):
detailIconSchemeHandler.currentArticle = article
- rendering = ArticleRenderer.articleHTML(article: article, theme: theme)
+ rendering = ArticleRenderer.articleHTML(article: article, theme: theme, routesThumbnailImages: routesThumbnailImages)
case .extracted(let article, let extractedArticle, _):
detailIconSchemeHandler.currentArticle = article
- rendering = ArticleRenderer.articleHTML(article: article, extractedArticle: extractedArticle, theme: theme)
+ rendering = ArticleRenderer.articleHTML(article: article, extractedArticle: extractedArticle, theme: theme, routesThumbnailImages: routesThumbnailImages)
}
let substitutions = [
diff --git a/Mac/MainWindow/Detail/main_mac.js b/Mac/MainWindow/Detail/main_mac.js
index 1a2e0fbf6..00b2b113d 100644
--- a/Mac/MainWindow/Detail/main_mac.js
+++ b/Mac/MainWindow/Detail/main_mac.js
@@ -30,6 +30,11 @@ function selectedHTML() {
container.querySelectorAll("a[href]").forEach(function(anchor) {
anchor.setAttribute("href", anchor.href);
});
+ // Images served from the timeline’s copy would break outside this page.
+ container.querySelectorAll("img[data-nnw-src]").forEach(function(image) {
+ image.setAttribute("src", image.getAttribute("data-nnw-src"));
+ image.removeAttribute("data-nnw-src");
+ });
// A single-paragraph selection doesn't need its wrapper.
if (container.childNodes.length === 1 && container.firstChild.nodeName === "P") {
return container.firstChild.innerHTML;
diff --git a/Mac/MainWindow/IconView.swift b/Mac/MainWindow/IconView.swift
index f2c1e4785..c40e87faa 100644
--- a/Mac/MainWindow/IconView.swift
+++ b/Mac/MainWindow/IconView.swift
@@ -59,9 +59,6 @@ final class IconView: NSView {
return imageView.frame.size.height < bounds.size.height
}
- private static var lightBackgroundColor = Assets.Colors.iconLightBackground
- private static var darkBackgroundColor = Assets.Colors.iconDarkBackground
-
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
commonInit()
@@ -93,9 +90,9 @@ final class IconView: NSView {
guard !(iconImage?.isBackgroundSuppressed ?? false) else { return }
guard hasExposedVerticalBackground || !isDiscernable else { return }
- let color = NSApplication.shared.effectiveAppearance.isDarkMode ? IconView.darkBackgroundColor : IconView.lightBackgroundColor
- color.set()
- dirtyRect.fill()
+ // The fill is translucent, so it’s blended, not copied.
+ Assets.Colors.iconBackground.set()
+ dirtyRect.fill(using: .sourceOver)
}
}
diff --git a/Mac/MainWindow/MainWindowController.swift b/Mac/MainWindow/MainWindowController.swift
index 833b3bfbc..b9abbd3b7 100644
--- a/Mac/MainWindow/MainWindowController.swift
+++ b/Mac/MainWindow/MainWindowController.swift
@@ -53,7 +53,7 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
private var splitViewController: NSSplitViewController?
// Column layout only: the vertical split holding the timeline above the article view.
private var contentSplitViewController: NSSplitViewController?
- private var timelineLayout = AppDefaults.shared.timelineLayout
+ private var timelineLayout = AppDefaults.timelineLayout
// Geometry for the layout that isn’t showing, so a round trip through the other layout keeps it.
private var rememberedStandardLayoutWidths = [Int]()
private var rememberedColumnLayoutTimelineHeight = 0
@@ -67,10 +67,18 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
didSet {
timelineContainerViewController?.showTimeline(for: timelineSourceMode)
detailViewController?.showDetail(for: timelineSourceMode)
+ updateStatusBarLink()
}
}
private var searchSmartFeed: SmartFeed?
private var restoreArticleWindowScrollY: CGFloat?
+ // Holds the split view controller and the status bar.
+ private let mainWindowContentViewController = MainWindowContentViewController()
+ private var mouseoverLink: String? {
+ didSet {
+ updateStatusBarLink()
+ }
+ }
// MARK: - NSWindowController
@@ -99,7 +107,12 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
timelineContainerViewController.delegate = self
self.timelineContainerViewController = timelineContainerViewController
- detailViewController = DetailViewController()
+ let detailViewController = DetailViewController()
+ detailViewController.delegate = self
+ self.detailViewController = detailViewController
+
+ mainWindowContentViewController.statusBarView.delegate = self
+ updateStatusBarVisibility()
installSplitViewController(for: timelineLayout)
@@ -155,7 +168,7 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
let state = savableState()
Self.logger.debug("MainWindowController: Saving state to UserDefaults: \(state)")
let data = try? NSKeyedArchiver.archivedData(withRootObject: state, requiringSecureCoding: true)
- AppDefaults.shared.secureWindowState = data
+ AppDefaults.secureWindowState = data
// Don't save the frame in full screen — it would replace the saved windowed frame with the screen's frame.
if let window, !window.styleMask.contains(.fullScreen) {
window.saveFrame(usingName: windowAutosaveName)
@@ -163,16 +176,16 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
}
func restoreStateFromUserDefaults() {
- if let data = AppDefaults.shared.secureWindowState,
+ if let data = AppDefaults.secureWindowState,
let state = try? NSKeyedUnarchiver.unarchivedObject(ofClass: MainWindowState.self, from: data) {
Self.logger.debug("MainWindowController: restoring state from UserDefaults: \(state)")
window?.setFrameUsingName(windowAutosaveName, force: true)
restoreState(from: state)
- } else if let state = AppDefaults.shared.legacyWindowState {
+ } else if let state = AppDefaults.legacyWindowState {
// Migrate from previous window state data. Delete data when finished.
window?.setFrameUsingName(windowAutosaveName, force: true)
restoreLegacyState(from: state)
- AppDefaults.shared.deleteLegacyWindowState()
+ AppDefaults.deleteLegacyWindowState()
}
}
@@ -185,10 +198,11 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
}
private func userDefaultsDidChange() {
- let layout = AppDefaults.shared.timelineLayout
+ let layout = AppDefaults.timelineLayout
if layout != timelineLayout {
installSplitViewController(for: layout)
}
+ updateStatusBarVisibility()
}
@objc func refreshProgressDidChange(_ note: Notification) {
@@ -333,6 +347,10 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
return validateSortDirection(item, direction: .orderedDescending)
}
+ if let isShown = SidebarViewController.smartFeedIsShown(forGoToAction: item.action) {
+ return isShown
+ }
+
return true
}
@@ -401,7 +419,7 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
}
@IBAction func openInBrowser(_ sender: Any?) {
- if AppDefaults.shared.openInBrowserInBackground {
+ if AppDefaults.openInBrowserInBackground {
window?.makeKeyAndOrderFront(self)
}
openArticleInBrowser(sender)
@@ -413,11 +431,11 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations
}
@IBAction func openInBrowserUsingOppositeOfSettings(_ sender: Any?) {
- if !AppDefaults.shared.openInBrowserInBackground {
+ if !AppDefaults.openInBrowserInBackground {
window?.makeKeyAndOrderFront(self)
}
if let link = currentLink {
- Browser.open(link, inBackground: !AppDefaults.shared.openInBrowserInBackground)
+ Browser.open(link, inBackground: !AppDefaults.openInBrowserInBackground)
}
}
@@ -732,6 +750,7 @@ extension MainWindowController: TimelineContainerViewControllerDelegate {
}
detailViewController?.setState(detailState, mode: mode)
+ updateStatusBarLink()
}
func timelineRequestedFeedSelection(_: TimelineContainerViewController, feed: Feed) {
@@ -855,6 +874,48 @@ extension MainWindowController: ScriptingMainWindowController {
}
}
+// MARK: - DetailViewControllerDelegate
+
+extension MainWindowController: DetailViewControllerDelegate {
+
+ func detailViewController(_ detailViewController: DetailViewController, mouseoverLinkDidChange link: String?) {
+ mouseoverLink = link
+ }
+}
+
+// MARK: - MainWindowStatusBarViewDelegate
+
+extension MainWindowController: MainWindowStatusBarViewDelegate {
+
+ func statusBarViewGearMenu(_ statusBarView: MainWindowStatusBarView) -> NSMenu? {
+ guard let menu = sidebarViewController?.statusBarMenu() else {
+ return nil
+ }
+
+ var index = 0
+ if AccountManager.shared.canRefresh {
+ menu.insertItem(withTitle: NSLocalizedString("Refresh", comment: "Refresh"), action: #selector(AppDelegate.refreshAll(_:)), keyEquivalent: "", at: index)
+ index += 1
+ }
+
+ let isSidebarHidden = sidebarSplitViewItem?.isCollapsed ?? false
+ let sidebarTitle = isSidebarHidden ? NSLocalizedString("Show Sidebar", comment: "Command") : NSLocalizedString("Hide Sidebar", comment: "Command")
+ menu.insertItem(withTitle: sidebarTitle, action: #selector(NSSplitViewController.toggleSidebar(_:)), keyEquivalent: "", at: index)
+ menu.insertItem(NSMenuItem.separator(), at: index + 1)
+
+ return menu
+ }
+
+ func statusBarView(_ statusBarView: MainWindowStatusBarView, moveSidebarDividerTo position: CGFloat) {
+ guard let splitView = splitViewController?.splitView else {
+ return
+ }
+ let positionInWindow = statusBarView.convert(NSPoint(x: position, y: 0), to: nil)
+ let positionInSplitView = splitView.convert(positionInWindow, from: nil)
+ splitView.setPosition(positionInSplitView.x, ofDividerAt: 0)
+ }
+}
+
// MARK: - NSToolbarDelegate
extension NSToolbarItem.Identifier {
@@ -958,7 +1019,7 @@ extension MainWindowController: NSToolbarDelegate {
let description = NSLocalizedString("Article Theme", comment: "Article Theme")
toolbarItem.toolTip = description
toolbarItem.label = description
- toolbarItem.menu = makeArticleThemeMenu()
+ toolbarItem.menu = ArticleThemesManager.shared.makeArticleThemeMenu()
return toolbarItem
case .search:
@@ -1093,7 +1154,10 @@ private extension MainWindowController {
}
splitViewController = newSplitViewController
timelineLayout = layout
- window.contentViewController = newSplitViewController
+ if window.contentViewController !== mainWindowContentViewController {
+ window.contentViewController = mainWindowContentViewController
+ }
+ mainWindowContentViewController.splitViewController = newSplitViewController
if window.frame != savedFrame && !window.styleMask.contains(.fullScreen) {
window.setFrame(savedFrame, display: false)
}
@@ -1117,6 +1181,7 @@ private extension MainWindowController {
currentTimelineViewController?.focus()
}
window.recalculateKeyViewLoop()
+ observeSplitViewForStatusBar()
invalidateRestorableState()
}
@@ -1205,7 +1270,7 @@ private extension MainWindowController {
return (splitViewController, contentSplitViewController)
}
- func makeEmptySplitViewController(isVertical: Bool, splitView: NSSplitView = NSSplitView()) -> NSSplitViewController {
+ func makeEmptySplitViewController(isVertical: Bool, splitView: NSSplitView = MainWindowSplitView()) -> NSSplitViewController {
let splitViewController = NSSplitViewController()
splitViewController.splitView = splitView
splitViewController.splitView.isVertical = isVertical
@@ -1486,7 +1551,7 @@ private extension MainWindowController {
}
func validateToggleArticleExtractor(_ item: NSValidatedUserInterfaceItem) -> Bool {
- guard !AppDefaults.shared.isDeveloperBuild else {
+ guard !AppDefaults.isDeveloperBuild else {
return false
}
@@ -1665,7 +1730,7 @@ private extension MainWindowController {
}
func setSubtitle(_ count: Int) {
- guard AppDefaults.shared.unreadCountDisplay == .count else {
+ guard AppDefaults.unreadCountDisplay == .count else {
window?.subtitle = ""
return
}
@@ -1771,12 +1836,12 @@ private extension MainWindowController {
let menu = NSMenu()
let newFeedItem = NSMenuItem()
- newFeedItem.title = NSLocalizedString("New Feed…", comment: "New Feed")
+ newFeedItem.title = NSLocalizedString("New Feed…", comment: "Command")
newFeedItem.action = #selector(AppDelegate.showAddFeedWindow(_:))
menu.addItem(newFeedItem)
let newFolderFeedItem = NSMenuItem()
- newFolderFeedItem.title = NSLocalizedString("New Folder…", comment: "New Folder")
+ newFolderFeedItem.title = NSLocalizedString("New Folder…", comment: "Command")
newFolderFeedItem.action = #selector(AppDelegate.showAddFolderWindow(_:))
menu.addItem(newFolderFeedItem)
@@ -1787,28 +1852,55 @@ private extension MainWindowController {
guard let toolbarItem = window?.toolbar?.existingItem(withIdentifier: .articleThemeMenu) as? NSMenuToolbarItem else {
return
}
- toolbarItem.menu = makeArticleThemeMenu()
+ toolbarItem.menu = ArticleThemesManager.shared.makeArticleThemeMenu()
}
- func makeArticleThemeMenu() -> NSMenu {
- let articleThemeMenu = NSMenu()
+ // MARK: - Status Bar
- let defaultThemeItem = NSMenuItem()
- defaultThemeItem.title = ArticleTheme.defaultTheme.name
- defaultThemeItem.action = #selector(selectArticleTheme(_:))
- defaultThemeItem.state = defaultThemeItem.title == ArticleThemesManager.shared.currentThemeName ? .on : .off
- articleThemeMenu.addItem(defaultThemeItem)
+ /// The status bar, when showing, takes the place of the detail view’s floating link overlay and the sidebar’s progress view.
+ func updateStatusBarVisibility() {
+ let showStatusBar = AppDefaults.showStatusBar
+ mainWindowContentViewController.isStatusBarHidden = !showStatusBar
+ detailViewController?.showsMouseoverLinkOverlay = !showStatusBar
+ sidebarViewController?.showsProgressView = !showStatusBar
+ }
- articleThemeMenu.addItem(NSMenuItem.separator())
+ func updateStatusBarLink() {
+ mainWindowContentViewController.statusBarView.link = mouseoverLink ?? currentLink
+ }
- for themeName in ArticleThemesManager.shared.themeNames {
- let themeItem = NSMenuItem()
- themeItem.title = themeName
- themeItem.action = #selector(selectArticleTheme(_:))
- themeItem.state = themeItem.title == ArticleThemesManager.shared.currentThemeName ? .on : .off
- articleThemeMenu.addItem(themeItem)
+ /// Tracks the sidebar divider in the status bar. Call after the split view controller is replaced.
+ func observeSplitViewForStatusBar() {
+ NotificationCenter.default.removeObserver(self, name: NSSplitView.didResizeSubviewsNotification, object: nil)
+ if let splitView = splitViewController?.splitView {
+ NotificationCenter.default.addObserver(self, selector: #selector(handleSplitViewDidResizeSubviews(_:)), name: NSSplitView.didResizeSubviewsNotification, object: splitView)
}
+ updateStatusBarSidebarDivider()
+ }
- return articleThemeMenu
+ @objc func handleSplitViewDidResizeSubviews(_ notification: Notification) {
+ updateStatusBarSidebarDivider()
+ }
+
+ func updateStatusBarSidebarDivider() {
+ let statusBarView = mainWindowContentViewController.statusBarView
+ guard let sidebarSplitViewItem, !sidebarSplitViewItem.isCollapsed, let splitView = splitViewController?.splitView, let sidebarPane = splitView.arrangedSubviews.first else {
+ statusBarView.sidebarDividerPosition = nil
+ return
+ }
+ // Use the split view’s sidebar pane, not the sidebar view: while the sidebar slides in,
+ // the sidebar view’s position lags a step behind the pane and isn’t updated after the last resize.
+ let dividerPositionInStatusBar = statusBarView.convert(NSPoint(x: sidebarPane.frame.maxX, y: 0), from: splitView)
+
+ // Starting with macOS 26, the content beside the sidebar extends under it, and the divider is a hairline
+ // at the sidebar’s trailing edge. Before that, the divider follows the sidebar.
+ let arrangedSubviews = splitView.arrangedSubviews
+ if arrangedSubviews.count > 1 {
+ let contentExtendsUnderSidebar = arrangedSubviews[1].frame.minX < sidebarPane.frame.maxX
+ let hairline = 1 / (window?.backingScaleFactor ?? 1)
+ statusBarView.sidebarDividerLineOffset = contentExtendsUnderSidebar ? -hairline : 0
+ statusBarView.sidebarDividerLineWidth = contentExtendsUnderSidebar ? hairline : splitView.dividerThickness
+ }
+ statusBarView.sidebarDividerPosition = dividerPositionInStatusBar.x
}
}
diff --git a/Mac/MainWindow/MainWindowSplitView.swift b/Mac/MainWindow/MainWindowSplitView.swift
new file mode 100644
index 000000000..952792aec
--- /dev/null
+++ b/Mac/MainWindow/MainWindowSplitView.swift
@@ -0,0 +1,22 @@
+//
+// MainWindowSplitView.swift
+// NetNewsWire
+//
+// Created by Brent Simmons on 11/7/26.
+// Copyright © 2026 Ranchero Software. All rights reserved.
+//
+
+import AppKit
+
+/// The main window’s split views. In light mode, the dividers are a little darker than the system’s.
+class MainWindowSplitView: NSSplitView {
+
+ private static let lightDividerColor = NSColor(srgbRed: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1)
+
+ override var dividerColor: NSColor {
+ if effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua {
+ return super.dividerColor
+ }
+ return Self.lightDividerColor
+ }
+}
diff --git a/Mac/MainWindow/NNW3/NNW3ImportController.swift b/Mac/MainWindow/NNW3/NNW3ImportController.swift
index 3e51eabb0..0d94f8625 100644
--- a/Mac/MainWindow/NNW3/NNW3ImportController.swift
+++ b/Mac/MainWindow/NNW3/NNW3ImportController.swift
@@ -82,7 +82,7 @@ private extension NNW3ImportController {
guard let account = accessoryViewController.selectedAccount else {
return
}
- AppDefaults.shared.importOPMLAccountID = account.accountID
+ AppDefaults.importOPMLAccountID = account.accountID
NNW3ImportController.importSubscriptionsPlist(subscriptionsPlistURL, into: account)
}
diff --git a/Mac/MainWindow/NNW3/NNW3OpenPanelAccessoryViewController.swift b/Mac/MainWindow/NNW3/NNW3OpenPanelAccessoryViewController.swift
index c62c6f1b4..73f681b84 100644
--- a/Mac/MainWindow/NNW3/NNW3OpenPanelAccessoryViewController.swift
+++ b/Mac/MainWindow/NNW3/NNW3OpenPanelAccessoryViewController.swift
@@ -43,7 +43,7 @@ final class NNW3OpenPanelAccessoryViewController: NSViewController {
menuItem.representedObject = account
menu.addItem(menuItem)
- if account.accountID == AppDefaults.shared.importOPMLAccountID {
+ if account.accountID == AppDefaults.importOPMLAccountID {
accountPopUpButton.select(menuItem)
}
}
diff --git a/Mac/MainWindow/OPML/ExportOPMLWindowController.swift b/Mac/MainWindow/OPML/ExportOPMLWindowController.swift
index e6a54407b..4f0b27d70 100644
--- a/Mac/MainWindow/OPML/ExportOPMLWindowController.swift
+++ b/Mac/MainWindow/OPML/ExportOPMLWindowController.swift
@@ -27,7 +27,7 @@ final class ExportOPMLWindowController: NSWindowController {
accountPopUpButton.menu = menu
let accounts: [Account] = AccountManager.shared.sortedAccounts
- let savedAccountID: String? = AppDefaults.shared.exportOPMLAccountID
+ let savedAccountID: String? = AppDefaults.exportOPMLAccountID
for oneAccount in accounts {
addMenuItem(to: menu, for: oneAccount, savedAccountID: savedAccountID)
@@ -75,7 +75,7 @@ final class ExportOPMLWindowController: NSWindowController {
}
let account = menuItem.representedObject as! Account
- AppDefaults.shared.exportOPMLAccountID = account.accountID
+ AppDefaults.exportOPMLAccountID = account.accountID
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.OK)
exportOPML(account: account)
diff --git a/Mac/MainWindow/OPML/ImportOPMLWindowController.swift b/Mac/MainWindow/OPML/ImportOPMLWindowController.swift
index 7f68d6ab3..e323f9eab 100644
--- a/Mac/MainWindow/OPML/ImportOPMLWindowController.swift
+++ b/Mac/MainWindow/OPML/ImportOPMLWindowController.swift
@@ -26,7 +26,7 @@ final class ImportOPMLWindowController: NSWindowController {
accountPopUpButton.menu = menu
let accounts: [Account] = AccountManager.shared.sortedActiveAccounts
- let savedAccountID: String? = AppDefaults.shared.importOPMLAccountID
+ let savedAccountID: String? = AppDefaults.importOPMLAccountID
for oneAccount in accounts {
if oneAccount.behaviors.contains(.disallowOPMLImports) {
@@ -77,7 +77,7 @@ final class ImportOPMLWindowController: NSWindowController {
}
let account = menuItem.representedObject as! Account
- AppDefaults.shared.importOPMLAccountID = account.accountID
+ AppDefaults.importOPMLAccountID = account.accountID
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.OK)
importOPML(account: account)
diff --git a/Mac/MainWindow/Sidebar/Base.lproj/SidebarView.xib b/Mac/MainWindow/Sidebar/Base.lproj/SidebarView.xib
index ebc3e88c9..27e6566fe 100644
--- a/Mac/MainWindow/Sidebar/Base.lproj/SidebarView.xib
+++ b/Mac/MainWindow/Sidebar/Base.lproj/SidebarView.xib
@@ -8,6 +8,7 @@
+
@@ -88,7 +89,7 @@
-
+
diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift
index 9809a6f77..0f4590184 100644
--- a/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift
+++ b/Mac/MainWindow/Sidebar/Cell/SidebarCell.swift
@@ -107,7 +107,7 @@ final class SidebarCell: NSTableCellView {
guard let cellAppearance = cellAppearance else {
return
}
- let layout = SidebarCellLayout(appearance: cellAppearance, cellSize: bounds.size, trailingEdge: trailingEdge(), shouldShowImage: shouldShowImage, textField: titleView, unreadCountView: unreadCountView)
+ let layout = SidebarCellLayout(appearance: cellAppearance, cellSize: bounds.size, shouldShowImage: shouldShowImage, textField: titleView, unreadCountView: unreadCountView)
layoutWith(layout)
}
@@ -119,7 +119,7 @@ final class SidebarCell: NSTableCellView {
}
override func accessibilityLabel() -> String? {
- guard let unreadText = AppDefaults.shared.unreadCountDisplay.accessibilityText(for: unreadCount) else {
+ guard let unreadText = AppDefaults.unreadCountDisplay.accessibilityText(for: unreadCount) else {
return name
}
return "\(name) \(unreadText)"
@@ -139,24 +139,6 @@ private extension SidebarCell {
view.translatesAutoresizingMaskIntoConstraints = false
}
- // Ask the outline view for the cell frame instead of trusting
- // the cell's own width, which can be stale while the outline view is tiling.
- func trailingEdge() -> CGFloat {
- var view = superview
- while let currentView = view {
- if let outlineView = currentView as? NSOutlineView {
- let row = outlineView.row(for: self)
- if row < 0 {
- return bounds.maxX
- }
- let cellFrame = outlineView.frameOfCell(atColumn: 0, row: row)
- return convert(NSPoint(x: cellFrame.maxX, y: 0), from: outlineView).x
- }
- view = currentView.superview
- }
- return bounds.maxX
- }
-
func layoutWith(_ layout: SidebarCellLayout) {
faviconImageView.setFrameIfNotEqual(layout.faviconRect)
titleView.setFrameIfNotEqual(layout.titleRect)
diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift
index fdf0dd96e..819cb8cd4 100644
--- a/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift
+++ b/Mac/MainWindow/Sidebar/Cell/SidebarCellAppearance.swift
@@ -16,17 +16,48 @@ struct SidebarCellAppearance: Equatable {
let textFieldFontSize: CGFloat
let textFieldFont: NSFont
- init(rowSizeStyle: NSTableView.RowSizeStyle) {
- switch rowSizeStyle {
+ private static let smallFontSize: CGFloat = 11
+ private static let mediumFontSize: CGFloat = 13
+ private static let largeFontSize: CGFloat = 15
+ private static let extraLargeFontSize: CGFloat = 17
+ private static let extraExtraLargeFontSize: CGFloat = 20
+
+ private static let smallImageSize = CGSize(width: 16, height: 16)
+ private static let mediumImageSize = CGSize(width: 19, height: 19)
+ private static let largeImageSize = CGSize(width: 22, height: 22)
+ private static let extraLargeImageSize = CGSize(width: 25, height: 25)
+ private static let extraExtraLargeImageSize = CGSize(width: 28, height: 28)
+
+ /// `systemRowSizeStyle` is used only when `textSize` is `.system`.
+ init(textSize: SidebarTextSize, systemRowSizeStyle: NSTableView.RowSizeStyle) {
+ switch textSize {
+ case .system:
+ switch systemRowSizeStyle {
+ case .small:
+ imageSize = Self.smallImageSize
+ textFieldFontSize = Self.smallFontSize
+ case .large:
+ imageSize = Self.largeImageSize
+ textFieldFontSize = Self.largeFontSize
+ default:
+ imageSize = Self.mediumImageSize
+ textFieldFontSize = Self.mediumFontSize
+ }
case .small:
- imageSize = CGSize(width: 16, height: 16)
- textFieldFontSize = 11
+ imageSize = Self.smallImageSize
+ textFieldFontSize = Self.smallFontSize
+ case .medium:
+ imageSize = Self.mediumImageSize
+ textFieldFontSize = Self.mediumFontSize
case .large:
- imageSize = CGSize(width: 22, height: 22)
- textFieldFontSize = 15
- default:
- imageSize = CGSize(width: 19, height: 19)
- textFieldFontSize = 13
+ imageSize = Self.largeImageSize
+ textFieldFontSize = Self.largeFontSize
+ case .extraLarge:
+ imageSize = Self.extraLargeImageSize
+ textFieldFontSize = Self.extraLargeFontSize
+ case .extraExtraLarge:
+ imageSize = Self.extraExtraLargeImageSize
+ textFieldFontSize = Self.extraExtraLargeFontSize
}
self.textFieldFont = NSFont.systemFont(ofSize: textFieldFontSize)
diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift
index 0b539b48b..218c18a71 100644
--- a/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift
+++ b/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift
@@ -16,9 +16,8 @@ import RSCore
let titleRect: CGRect
let unreadCountRect: CGRect
- init(appearance: SidebarCellAppearance, cellSize: NSSize, trailingEdge: CGFloat, shouldShowImage: Bool, textField: NSTextField, unreadCountView: UnreadCountView) {
+ init(appearance: SidebarCellAppearance, cellSize: NSSize, shouldShowImage: Bool, textField: NSTextField, unreadCountView: UnreadCountView) {
let bounds = NSRect(x: 0.0, y: 0.0, width: floor(cellSize.width), height: floor(cellSize.height))
- let maxX = floor(trailingEdge)
var rFavicon = NSRect.zero
if shouldShowImage {
@@ -41,7 +40,7 @@ import RSCore
var rUnread = NSRect.zero
if !unreadCountIsHidden {
rUnread.size = unreadCountSize
- rUnread.origin.x = maxX - unreadCountSize.width
+ rUnread.origin.x = bounds.maxX - unreadCountSize.width
rUnread = rUnread.centeredVertically(in: bounds)
let textFieldMaxX = rUnread.minX - appearance.unreadCountMarginLeft
if rTextField.maxX > textFieldMaxX {
@@ -50,8 +49,8 @@ import RSCore
}
self.unreadCountRect = rUnread
- if rTextField.maxX > maxX {
- rTextField.size.width = maxX - rTextField.minX
+ if rTextField.maxX > bounds.maxX {
+ rTextField.size.width = bounds.maxX - rTextField.minX
}
self.titleRect = rTextField
}
diff --git a/Mac/MainWindow/Sidebar/SidebarStatusBarView.swift b/Mac/MainWindow/Sidebar/SidebarProgressView.swift
similarity index 82%
rename from Mac/MainWindow/Sidebar/SidebarStatusBarView.swift
rename to Mac/MainWindow/Sidebar/SidebarProgressView.swift
index 2f8d02efc..9fd48a341 100644
--- a/Mac/MainWindow/Sidebar/SidebarStatusBarView.swift
+++ b/Mac/MainWindow/Sidebar/SidebarProgressView.swift
@@ -1,5 +1,5 @@
//
-// SidebarStatusBarView.swift
+// SidebarProgressView.swift
// NetNewsWire
//
// Created by Brent Simmons on 9/17/16.
@@ -12,12 +12,24 @@ import Articles
import RSWeb
import Account
-final class SidebarStatusBarView: NSView {
+final class SidebarProgressView: NSView {
@IBOutlet var progressIndicator: NSProgressIndicator!
@IBOutlet var progressLabel: NSTextField!
@IBOutlet var bottomConstraint: NSLayoutConstraint!
@IBOutlet var heightConstraint: NSLayoutConstraint!
+ /// When true, the view stays hidden and shows no progress.
+ /// When collapsed, this view sits just below the sidebar, unclipped — where the main window status bar is.
+ /// Its separator would double the status bar’s top line, so it’s hidden while suppressed.
+ var isSuppressed = false {
+ didSet {
+ if isSuppressed != oldValue {
+ isHidden = isSuppressed
+ updateUI()
+ }
+ }
+ }
+
private var isAnimatingProgress = false
nonisolated override var isFlipped: Bool {
@@ -50,7 +62,7 @@ final class SidebarStatusBarView: NSView {
}
}
-private extension SidebarStatusBarView {
+private extension SidebarProgressView {
// MARK: Progress
@@ -69,7 +81,7 @@ private extension SidebarStatusBarView {
superview?.layoutSubtreeIfNeeded()
NSAnimationContext.runAnimationGroup { context in
- context.duration = SidebarStatusBarView.animationDuration
+ context.duration = SidebarProgressView.animationDuration
context.allowsImplicitAnimation = true
bottomConstraint.constant = -(heightConstraint.constant)
superview?.layoutSubtreeIfNeeded()
@@ -89,7 +101,7 @@ private extension SidebarStatusBarView {
superview?.layoutSubtreeIfNeeded()
NSAnimationContext.runAnimationGroup { context in
- context.duration = SidebarStatusBarView.animationDuration
+ context.duration = SidebarProgressView.animationDuration
context.allowsImplicitAnimation = true
bottomConstraint.constant = 0
superview?.layoutSubtreeIfNeeded()
@@ -100,7 +112,7 @@ private extension SidebarStatusBarView {
let progressInfo = CombinedRefreshProgress.shared.progressInfo
- if progressInfo.isComplete {
+ if progressInfo.isComplete || isSuppressed {
stopProgressIfNeeded()
return
}
diff --git a/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift b/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift
index facf79ac2..3c5433134 100644
--- a/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift
+++ b/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift
@@ -41,6 +41,27 @@ extension SidebarViewController {
return nil
}
}
+
+ /// The status bar gear menu: New Feed and New Folder, then the contextual menu for the selection —
+ /// under a disabled item naming the selection, with its commands indented.
+ func statusBarMenu() -> NSMenu {
+ let statusBarMenu = menuForNoSelection()
+ let objects = selectedObjects
+ guard !objects.isEmpty, let selectionMenu = menu(for: objects), selectionMenu.numberOfItems > 0 else {
+ return statusBarMenu
+ }
+ statusBarMenu.addItem(NSMenuItem.separator())
+
+ let headerItem = NSMenuItem(title: statusBarMenuHeaderTitle(for: objects), action: nil, keyEquivalent: "")
+ headerItem.isEnabled = false
+ statusBarMenu.addItem(headerItem)
+
+ for item in selectionMenu.items {
+ item.indentationLevel = Self.statusBarMenuIndentationLevel
+ }
+ statusBarMenu.takeItems(from: selectionMenu)
+ return statusBarMenu
+ }
}
// MARK: Contextual Menu Actions
@@ -193,12 +214,31 @@ extension SidebarViewController: RenameWindowControllerDelegate {
private extension SidebarViewController {
+ static let statusBarMenuIndentationLevel = 1
+
+ /// The name of the one selected item, or a description of a multiple selection.
+ func statusBarMenuHeaderTitle(for objects: [AnyObject]) -> String {
+ if objects.count == 1, let displayNameProvider = objects.first as? DisplayNameProvider {
+ return displayNameProvider.nameForDisplay
+ }
+ if objects.allSatisfy({ $0 is Feed }) {
+ return NSLocalizedString("Multiple feeds", comment: "Status bar gear menu: header for a selection of several feeds")
+ }
+ if objects.allSatisfy({ $0 is Folder }) {
+ return NSLocalizedString("Multiple folders", comment: "Status bar gear menu: header for a selection of several folders")
+ }
+ if objects.allSatisfy({ $0 is PseudoFeed }) {
+ return NSLocalizedString("Multiple smart feeds", comment: "Status bar gear menu: header for a selection of several smart feeds")
+ }
+ return NSLocalizedString("Multiple selection", comment: "Status bar gear menu: header for a selection of different kinds of items")
+ }
+
func menuForNoSelection() -> NSMenu {
let menu = NSMenu(title: "")
- menu.addItem(withTitle: NSLocalizedString("New Feed", comment: "Command"), action: #selector(AppDelegate.showAddFeedWindow(_:)), keyEquivalent: "")
- menu.addItem(withTitle: NSLocalizedString("New Folder", comment: "Command"), action: #selector(AppDelegate.showAddFolderWindow(_:)), keyEquivalent: "")
+ menu.addItem(withTitle: NSLocalizedString("New Feed…", comment: "Command"), action: #selector(AppDelegate.showAddFeedWindow(_:)), keyEquivalent: "")
+ menu.addItem(withTitle: NSLocalizedString("New Folder…", comment: "Command"), action: #selector(AppDelegate.showAddFolderWindow(_:)), keyEquivalent: "")
return menu
}
diff --git a/Mac/MainWindow/Sidebar/SidebarViewController.swift b/Mac/MainWindow/Sidebar/SidebarViewController.swift
index bf349de33..b3b9ccfeb 100644
--- a/Mac/MainWindow/Sidebar/SidebarViewController.swift
+++ b/Mac/MainWindow/Sidebar/SidebarViewController.swift
@@ -26,9 +26,17 @@ extension Notification.Name {
@objc final class SidebarViewController: NSViewController, NSOutlineViewDelegate, NSMenuDelegate, UndoableCommandRunner {
@IBOutlet var outlineView: SidebarOutlineView!
+ @IBOutlet var progressView: SidebarProgressView?
weak var delegate: SidebarDelegate?
+ /// False when the main window status bar takes over refresh progress.
+ var showsProgressView = true {
+ didSet {
+ progressView?.isSuppressed = !showsProgressView
+ }
+ }
+
weak var splitViewItem: NSSplitViewItem?
var windowState: SidebarWindowState {
@@ -75,6 +83,8 @@ extension Notification.Name {
}
private static let rowViewIdentifier = NSUserInterfaceItemIdentifier(rawValue: "sidebarRow")
+ private static let extraLargeRowHeight: CGFloat = 36
+ private static let extraExtraLargeRowHeight: CGFloat = 42
private let keyboardDelegate = SidebarKeyboardDelegate()
// MARK: - NSViewController
@@ -84,6 +94,7 @@ extension Notification.Name {
}
override func viewDidLoad() {
+ progressView?.isSuppressed = !showsProgressView
outlineView.keyboardDelegate = keyboardDelegate
outlineView.dataSource = dataSource
outlineView.doubleAction = #selector(doubleClickedSidebar(_:))
@@ -93,18 +104,27 @@ extension Notification.Name {
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidInitialize(_:)), name: .UnreadCountDidInitialize, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleUnreadCountDisplaySettingDidChange(_:)), name: .unreadCountDisplaySettingDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleSidebarShowsIconsDidChange(_:)), name: .sidebarShowsIconsDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleSidebarTextSizeDidChange(_:)), name: .sidebarTextSizeDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleSidebarSmartFeedsVisibilityDidChange(_:)), name: .sidebarSmartFeedsVisibilityDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(containerChildrenDidChange(_:)), name: .ChildrenDidChange, object: nil)
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(accountStateDidChange(_:)), name: .AccountStateDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDidAddFeed(_:)), name: .UserDidAddFeed, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(batchUpdateDidPerform(_:)), name: .BatchUpdateDidPerform, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .FaviconDidBecomeAvailable, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleFeedIconImageDidChange(_:)), name: .feedIconImageDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleGrayscaleIconsDidChange(_:)), name: .grayscaleIconsDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(feedSettingDidChange(_:)), name: .feedSettingDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil)
DistributedNotificationCenter.default().addObserver(self, selector: #selector(appleSideBarDefaultIconSizeChanged(_:)), name: .appleSideBarDefaultIconSizeChanged, object: nil)
+ if let clipView = outlineView.enclosingScrollView?.contentView {
+ clipView.postsFrameChangedNotifications = true
+ NotificationCenter.default.addObserver(self, selector: #selector(handleClipViewFrameDidChange(_:)), name: NSView.frameDidChangeNotification, object: clipView)
+ }
+
+ updateRowSizeStyle()
outlineView.reloadData()
// Expand top level items by default. If there is state to restore, overlay this.
@@ -232,6 +252,31 @@ extension Notification.Name {
}
}
+ @objc func handleSidebarShowsIconsDidChange(_ notification: Notification) {
+ prefetchFeedIcons()
+ applyToAvailableCells(configure)
+ }
+
+ @objc func handleGrayscaleIconsDidChange(_ notification: Notification) {
+ applyToAvailableCells(configure)
+ }
+
+ @objc func handleSidebarSmartFeedsVisibilityDidChange(_ notification: Notification) {
+ rebuildTreeAndRestoreSelection()
+ expandNodes()
+ }
+
+ @objc func handleSidebarTextSizeDidChange(_ notification: Notification) {
+ updateRowSizeStyle()
+ let savedSelection = selectedNodes
+ outlineView.reloadData()
+ restoreSelection(to: savedSelection, sendNotificationIfChanged: true)
+ }
+
+ @objc func handleClipViewFrameDidChange(_ notification: Notification) {
+ fitOutlineViewToVisibleWidth()
+ }
+
@objc func containerChildrenDidChange(_ note: Notification) {
rebuildTreeAndRestoreSelection()
}
@@ -255,12 +300,10 @@ extension Notification.Name {
revealAndSelectRepresentedObject(feed as AnyObject)
}
- @objc func faviconDidBecomeAvailable(_ note: Notification) {
- applyToAvailableCells(configureFavicon)
- }
-
- @objc func feedIconDidBecomeAvailable(_ note: Notification) {
- guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed else { return }
+ @objc func handleFeedIconImageDidChange(_ notification: Notification) {
+ guard let feed = notification.userInfo?[UserInfoKey.feed] as? Feed else {
+ return
+ }
configureCellsForRepresentedObject(feed)
}
@@ -284,6 +327,9 @@ extension Notification.Name {
}
@objc func appleSideBarDefaultIconSizeChanged(_ note: Notification) {
+ guard AppDefaults.sidebarTextSize == .system else {
+ return
+ }
// The outline view doesn't have the new row style size set yet when we get
// this notification, so give it half a second to catch up.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
@@ -321,7 +367,7 @@ extension Notification.Name {
guard outlineView.clickedRow == outlineView.selectedRow else {
return
}
- if AppDefaults.shared.feedDoubleClickMarkAsRead, let articles = singleSelectedFeed?.fetchUnreadArticles() {
+ if AppDefaults.feedDoubleClickMarkAsRead, let articles = singleSelectedFeed?.fetchUnreadArticles() {
if let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: Array(articles), markingRead: true, undoManager: undoManager) {
runCommand(markReadCommand)
}
@@ -476,6 +522,9 @@ extension Notification.Name {
delegate?.sidebarInvalidatedRestorationState(self)
}
+ guard AppDefaults.sidebarShowsIcons else {
+ return
+ }
var feeds = [Feed]()
collectExpandedFeeds(in: node, into: &feeds)
IconImageCache.shared.prefetchImagesForFeeds(feeds)
@@ -564,14 +613,47 @@ extension SidebarViewController: NSUserInterfaceValidations {
if item.action == #selector(copy(_:)) {
return NSPasteboard.general.canCopyAtLeastOneObject(selectedObjects)
}
+ if let isShown = Self.smartFeedIsShown(forGoToAction: item.action) {
+ return isShown
+ }
return true
}
+
+ /// Whether the smart feed that a Go menu action selects is shown in the sidebar. Nil for other actions.
+ static func smartFeedIsShown(forGoToAction action: Selector?) -> Bool? {
+ switch action {
+ case #selector(gotoToday(_:)):
+ AppDefaults.showTodayFeed
+ case #selector(gotoAllUnread(_:)):
+ AppDefaults.showUnreadFeed
+ case #selector(gotoStarred(_:)):
+ AppDefaults.showStarredFeed
+ default:
+ nil
+ }
+ }
}
// MARK: - Private
private extension SidebarViewController {
+ /// The outline view doesn’t resize its rows when the scroller appears or disappears,
+ /// which leaves the selection highlight at a stale width.
+ ///
+ func fitOutlineViewToVisibleWidth() {
+ guard let scrollView = outlineView.enclosingScrollView else {
+ return
+ }
+ let contentInsets = scrollView.contentInsets
+ let visibleWidth = scrollView.contentView.bounds.width - contentInsets.left - contentInsets.right
+ guard visibleWidth > 0, outlineView.frame.width != visibleWidth else {
+ return
+ }
+ outlineView.setFrameSize(NSSize(width: visibleWidth, height: outlineView.frame.height))
+ outlineView.sizeLastColumnToFit()
+ }
+
var accountNodes: [Account] {
return treeController.rootNode.childNodes.compactMap { $0.representedObject as? Account }
}
@@ -675,7 +757,29 @@ private extension SidebarViewController {
}
}
+ func updateRowSizeStyle() {
+ switch AppDefaults.sidebarTextSize {
+ case .system:
+ outlineView.rowSizeStyle = .default
+ case .small:
+ outlineView.rowSizeStyle = .small
+ case .medium:
+ outlineView.rowSizeStyle = .medium
+ case .large:
+ outlineView.rowSizeStyle = .large
+ case .extraLarge:
+ outlineView.rowSizeStyle = .custom
+ outlineView.rowHeight = Self.extraLargeRowHeight
+ case .extraExtraLarge:
+ outlineView.rowSizeStyle = .custom
+ outlineView.rowHeight = Self.extraExtraLargeRowHeight
+ }
+ }
+
func prefetchFeedIcons() {
+ guard AppDefaults.sidebarShowsIcons else {
+ return
+ }
var feeds = [Feed]()
collectExpandedFeeds(in: treeController.rootNode, into: &feeds)
IconImageCache.shared.prefetchImagesForFeeds(feeds)
@@ -847,12 +951,12 @@ private extension SidebarViewController {
}
func configure(_ cell: SidebarCell, _ node: Node) {
- cell.cellAppearance = SidebarCellAppearance(rowSizeStyle: outlineView.effectiveRowSizeStyle)
+ cell.cellAppearance = SidebarCellAppearance(textSize: AppDefaults.sidebarTextSize, systemRowSizeStyle: outlineView.effectiveRowSizeStyle)
cell.name = nameFor(node)
configureUnreadCount(cell, node)
cell.updateUnreadCountView() // A reused cell may predate a display setting change
configureFavicon(cell, node)
- cell.shouldShowImage = node.representedObject is SmallIconProvider
+ cell.shouldShowImage = AppDefaults.sidebarShowsIcons && node.representedObject is SmallIconProvider
}
func configureUnreadCount(_ cell: SidebarCell, _ node: Node) {
@@ -860,7 +964,7 @@ private extension SidebarViewController {
}
func configureFavicon(_ cell: SidebarCell, _ node: Node) {
- cell.iconImage = imageFor(node)
+ cell.iconImage = AppDefaults.sidebarShowsIcons ? imageFor(node) : nil
}
func configureGroupCell(_ cell: NSTableCellView, _ node: Node) {
@@ -868,8 +972,8 @@ private extension SidebarViewController {
}
func imageFor(_ node: Node) -> IconImage? {
- if let feed = node.representedObject as? Feed, let feedIcon = IconImageCache.shared.imageForFeed(feed) {
- return feedIcon
+ if let sidebarItem = node.representedObject as? SidebarItem, let iconImage = IconImageCache.shared.imageForFeed(sidebarItem) {
+ return iconImage
}
if let smallIconProvider = node.representedObject as? SmallIconProvider {
return smallIconProvider.smallIcon
diff --git a/Mac/MainWindow/Sidebar/UnreadCountView.swift b/Mac/MainWindow/Sidebar/UnreadCountView.swift
index 9e19f30b4..28ff295e3 100644
--- a/Mac/MainWindow/Sidebar/UnreadCountView.swift
+++ b/Mac/MainWindow/Sidebar/UnreadCountView.swift
@@ -54,11 +54,11 @@ final class UnreadCountView: NSView {
}
/// Text for the unread count, or nil when nothing should be drawn.
var unreadCountText: String? {
- AppDefaults.shared.unreadCountDisplay.text(for: unreadCount)
+ AppDefaults.unreadCountDisplay.text(for: unreadCount)
}
private var showsDot: Bool {
- AppDefaults.shared.unreadCountDisplay.showsDot(for: unreadCount)
+ AppDefaults.unreadCountDisplay.showsDot(for: unreadCount)
}
var isSelected: Bool = false {
diff --git a/Mac/MainWindow/StatusBar/MainWindowContentViewController.swift b/Mac/MainWindow/StatusBar/MainWindowContentViewController.swift
new file mode 100644
index 000000000..c52040d7f
--- /dev/null
+++ b/Mac/MainWindow/StatusBar/MainWindowContentViewController.swift
@@ -0,0 +1,88 @@
+//
+// MainWindowContentViewController.swift
+// NetNewsWire
+//
+// Created by Brent Simmons on 10/11/26.
+// Copyright © 2026 Ranchero Software. All rights reserved.
+//
+
+import AppKit
+
+/// The main window’s content where the status bar is available: the split view controller above the status bar.
+/// The split view controller is swapped when the timeline layout changes. The status bar stays.
+final class MainWindowContentViewController: NSViewController {
+
+ let statusBarView = MainWindowStatusBarView()
+
+ var splitViewController: NSSplitViewController? {
+ didSet {
+ if splitViewController !== oldValue {
+ replaceSplitViewController(oldValue)
+ }
+ }
+ }
+
+ var isStatusBarHidden = false {
+ didSet {
+ if isStatusBarHidden != oldValue {
+ updateStatusBarVisibility()
+ }
+ }
+ }
+
+ private var splitViewBottomToStatusBarConstraint: NSLayoutConstraint?
+ private var splitViewBottomToEdgeConstraint: NSLayoutConstraint?
+
+ override func loadView() {
+ view = NSView()
+
+ statusBarView.translatesAutoresizingMaskIntoConstraints = false
+ view.addSubview(statusBarView)
+ NSLayoutConstraint.activate([
+ statusBarView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
+ statusBarView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
+ statusBarView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
+ ])
+ }
+}
+
+// MARK: - Private
+
+private extension MainWindowContentViewController {
+
+ func replaceSplitViewController(_ oldSplitViewController: NSSplitViewController?) {
+ if let oldSplitViewController {
+ oldSplitViewController.view.removeFromSuperview()
+ oldSplitViewController.removeFromParent()
+ }
+ splitViewBottomToStatusBarConstraint = nil
+ splitViewBottomToEdgeConstraint = nil
+
+ guard let splitViewController else {
+ return
+ }
+
+ addChild(splitViewController)
+ let splitView = splitViewController.view
+ splitView.translatesAutoresizingMaskIntoConstraints = false
+ view.addSubview(splitView, positioned: .below, relativeTo: statusBarView)
+
+ splitViewBottomToStatusBarConstraint = splitView.bottomAnchor.constraint(equalTo: statusBarView.topAnchor)
+ splitViewBottomToEdgeConstraint = splitView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
+ NSLayoutConstraint.activate([
+ splitView.topAnchor.constraint(equalTo: view.topAnchor),
+ splitView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
+ splitView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
+ ])
+ updateStatusBarVisibility()
+ }
+
+ func updateStatusBarVisibility() {
+ statusBarView.isHidden = isStatusBarHidden
+ // Deactivate before activating so the two bottom constraints never conflict.
+ splitViewBottomToStatusBarConstraint?.isActive = false
+ splitViewBottomToEdgeConstraint?.isActive = false
+ let activeConstraint = isStatusBarHidden ? splitViewBottomToEdgeConstraint : splitViewBottomToStatusBarConstraint
+ activeConstraint?.isActive = true
+ }
+}
diff --git a/Mac/MainWindow/StatusBar/MainWindowStatusBarView.swift b/Mac/MainWindow/StatusBar/MainWindowStatusBarView.swift
new file mode 100644
index 000000000..35780c05c
--- /dev/null
+++ b/Mac/MainWindow/StatusBar/MainWindowStatusBarView.swift
@@ -0,0 +1,546 @@
+//
+// MainWindowStatusBarView.swift
+// NetNewsWire
+//
+// Created by Brent Simmons on 10/11/26.
+// Copyright © 2026 Ranchero Software. All rights reserved.
+//
+
+import AppKit
+import Account
+import RSCore
+
+@MainActor protocol MainWindowStatusBarViewDelegate: AnyObject {
+ func statusBarViewGearMenu(_ statusBarView: MainWindowStatusBarView) -> NSMenu?
+ /// `position` is in the status bar’s coordinates.
+ func statusBarView(_ statusBarView: MainWindowStatusBarView, moveSidebarDividerTo position: CGFloat)
+}
+
+/// The bar along the bottom of the main window: gear menu, count, sidebar grip, article link, theme menu.
+/// The left section lines up with the sidebar, and the sidebar divider continues down through the bar. Dragging at the divider moves it.
+/// Subviews are laid out manually in `layout()`.
+final class MainWindowStatusBarView: NSView {
+
+ weak var delegate: MainWindowStatusBarViewDelegate?
+
+ /// The link to show — the hovered link or the selected article’s link.
+ var link: String? {
+ didSet {
+ if link != oldValue {
+ updateLinkLabel()
+ }
+ }
+ }
+
+ /// Where the split view draws the divider line, relative to `sidebarDividerPosition`, and how wide.
+ /// The line through the bar uses these so it lines up with the divider above it.
+ var sidebarDividerLineOffset: CGFloat = 0 {
+ didSet {
+ needsDisplay = true
+ }
+ }
+ var sidebarDividerLineWidth: CGFloat = 1 {
+ didSet {
+ needsDisplay = true
+ }
+ }
+
+ /// The sidebar divider’s x position in this view’s coordinates, or nil when the sidebar is collapsed.
+ var sidebarDividerPosition: CGFloat? {
+ didSet {
+ if sidebarDividerPosition != oldValue {
+ // With the sidebar collapsed, the left section is just the gear and progress.
+ splitHandleView.isHidden = sidebarDividerPosition == nil
+ countLabel.isHidden = sidebarDividerPosition == nil
+ needsLayout = true
+ needsDisplay = true
+ }
+ }
+ }
+
+ // Measured from the mockup: 32 points including the top line.
+ static let height: CGFloat = 32
+
+ private let gearButton = StatusBarGearButton()
+ private let progressIndicator = NSProgressIndicator()
+ private let countLabel = NSTextField(labelWithString: "")
+ private let splitHandleView = StatusBarSplitHandleView()
+ private let linkLabel = NSTextField(labelWithString: "")
+ private let themePopUpButton = NSPopUpButton(frame: .zero, pullsDown: false)
+ private var dragStartDividerPosition: CGFloat?
+
+ private static let fontSize: CGFloat = 12
+ private static let topLineThickness: CGFloat = 1
+ private static let leadingMargin: CGFloat = 15
+ // The standard window-edge margin, applied to the theme pop-up button’s alignment rect. It keeps the
+ // button clear of the window’s bottom-right resize area.
+ private static let trailingMargin: CGFloat = 20
+ private static let spacingAfterGear: CGFloat = 12
+ // The count’s clickable area ends this far before the sidebar’s edge.
+ private static let countClickAreaTrailingInset: CGFloat = 20
+ // With the sidebar collapsed, the left section ends this far after its last item.
+ private static let leftSectionTrailingInsetWithoutSidebar: CGFloat = 6
+ private static let progressSpacing: CGFloat = 6
+ // The text field has its own inset, so the link’s text starts 13 points after the divider.
+ private static let spacingAfterDivider: CGFloat = 12.5
+ private static let spacingBeforeThemeMenu: CGFloat = 8
+ private static let progressIndicatorWidth: CGFloat = 40
+
+ private static let topLineColor = dynamicColor(lightWhite: 168 / 255, darkWhite: 0.04)
+ // A hairline just below the top line, so the bar looks raised.
+ private static let highlightColor = NSColor(name: nil) { appearance in
+ NSColor(white: 1, alpha: isDark(appearance) ? 0.07 : 0.7)
+ }
+ // Lighter than the grip.
+ private static let dividerColor = dynamicColor(lightWhite: 176 / 255, darkWhite: 0.28)
+ private static let gripColor = dynamicColor(lightWhite: 120 / 255, darkWhite: 0.45)
+
+ // The ||| grip: three hairlines, the last one 6.5 points before the divider.
+ private static let gripLineCount = 3
+ private static let gripLineInterval: CGFloat = 5
+ private static let gripLineHeight: CGFloat = 12
+ private static let gripTrailingInset: CGFloat = 6.5
+ // The drag area covers the grip and extends past the divider.
+ private static let dragAreaReachBeforeDivider: CGFloat = 17
+ private static let dragAreaReachAfterDivider: CGFloat = 6
+ private static let textColor = dynamicColor(lightWhite: 44 / 255, darkWhite: 0.85)
+ private static let gradient = NSGradient(starting: dynamicColor(lightWhite: 200 / 255, darkWhite: 0.14), ending: dynamicColor(lightWhite: 236 / 255, darkWhite: 0.22))
+ // Bottom to top, so the gradient starts with the darker color at the bottom.
+ private static let gradientAngle: CGFloat = 90
+
+ /// The etched look: a light line just below the text and icons. In dark mode, a dark line.
+ static let etchedShadow: NSShadow = {
+ let shadow = NSShadow()
+ shadow.shadowOffset = NSSize(width: 0, height: -1)
+ shadow.shadowBlurRadius = 0
+ shadow.shadowColor = NSColor(name: nil) { appearance in
+ isDark(appearance) ? NSColor(white: 0, alpha: 0.5) : NSColor(white: 1, alpha: 0.65)
+ }
+ return shadow
+ }()
+
+ override init(frame frameRect: NSRect) {
+ super.init(frame: frameRect)
+ commonInit()
+ }
+
+ required init?(coder: NSCoder) {
+ super.init(coder: coder)
+ commonInit()
+ }
+
+ override var isOpaque: Bool {
+ true
+ }
+
+ override func layout() {
+ super.layout()
+
+ // The content area is everything below the top line.
+ let contentHeight = bounds.height - Self.topLineThickness
+
+ gearButton.frame = NSRect(x: Self.leadingMargin, y: 0, width: gearButton.intrinsicContentSize.width, height: contentHeight)
+
+ var leftContentMaxX = gearButton.frame.maxX
+ var x = leftContentMaxX + Self.spacingAfterGear
+ if !progressIndicator.isHidden {
+ leftContentMaxX = place(progressIndicator, x: x, width: Self.progressIndicatorWidth, contentHeight: contentHeight).maxX
+ x = leftContentMaxX + Self.progressSpacing
+ }
+
+ // The count shows only with the sidebar. It fills the space up to the grip, so all of it is clickable.
+ if let sidebarDividerPosition {
+ let countMaxX = sidebarDividerPosition - Self.countClickAreaTrailingInset
+ place(countLabel, x: x, width: countMaxX - x, contentHeight: contentHeight)
+ }
+
+ let leftSectionMaxX = sidebarDividerPosition ?? leftContentMaxX + Self.leftSectionTrailingInsetWithoutSidebar
+ splitHandleView.frame = NSRect(x: leftSectionMaxX - Self.dragAreaReachBeforeDivider, y: 0, width: Self.dragAreaReachBeforeDivider + Self.dragAreaReachAfterDivider, height: contentHeight)
+
+ var linkMaxX = bounds.maxX - Self.trailingMargin
+ if !themePopUpButton.isHidden {
+ let themeWidth = themePopUpButton.intrinsicContentSize.width
+ linkMaxX = place(themePopUpButton, x: bounds.maxX - Self.trailingMargin - themeWidth, width: themeWidth, contentHeight: contentHeight).minX - Self.spacingBeforeThemeMenu
+ }
+
+ let linkX = leftSectionMaxX + Self.spacingAfterDivider
+ place(linkLabel, x: linkX, width: linkMaxX - linkX, contentHeight: contentHeight)
+ }
+
+ override func draw(_ dirtyRect: NSRect) {
+ // Draw within bounds only: views don’t clip to bounds by default, and dirtyRect can extend past them.
+ if let gradient = Self.gradient {
+ gradient.draw(in: bounds, angle: Self.gradientAngle)
+ }
+
+ Self.topLineColor.setFill()
+ NSRect(x: bounds.minX, y: bounds.maxY - Self.topLineThickness, width: bounds.width, height: Self.topLineThickness).fill()
+
+ let hairline = 1 / (window?.backingScaleFactor ?? 1)
+ Self.highlightColor.setFill()
+ NSRect(x: bounds.minX, y: bounds.maxY - Self.topLineThickness - hairline, width: bounds.width, height: hairline).fill()
+
+ // The sidebar divider continues through the bar as a hairline, with the ||| grip just before it.
+ guard let sidebarDividerPosition else {
+ return
+ }
+ Self.dividerColor.setFill()
+ let dividerX = sidebarDividerPosition + sidebarDividerLineOffset
+ let contentHeight = bounds.height - Self.topLineThickness
+ NSRect(x: dividerX, y: bounds.minY, width: sidebarDividerLineWidth, height: contentHeight).fill()
+
+ // Each grip line is etched, like the text: a highlight hairline just to its right.
+ let gripY = floor((contentHeight - Self.gripLineHeight) / 2)
+ let gripEtchColor = Self.etchedShadow.shadowColor
+ for index in 0.. Bool {
+ guard menuItem.action == #selector(copyLink(_:)) else {
+ return true
+ }
+ guard let link else {
+ return false
+ }
+ return !link.isEmpty
+ }
+}
+
+// MARK: - StatusBarGearButtonDelegate
+
+extension MainWindowStatusBarView: StatusBarGearButtonDelegate {
+
+ func gearButtonMenu(_ gearButton: StatusBarGearButton) -> NSMenu? {
+ delegate?.statusBarViewGearMenu(self)
+ }
+}
+
+// MARK: - StatusBarSplitHandleViewDelegate
+
+extension MainWindowStatusBarView: StatusBarSplitHandleViewDelegate {
+
+ func splitHandleViewDidBeginDragging(_ splitHandleView: StatusBarSplitHandleView) {
+ dragStartDividerPosition = sidebarDividerPosition
+ }
+
+ func splitHandleView(_ splitHandleView: StatusBarSplitHandleView, didDragBy distance: CGFloat) {
+ guard let dragStartDividerPosition else {
+ return
+ }
+ delegate?.statusBarView(self, moveSidebarDividerTo: dragStartDividerPosition + distance)
+ }
+}
+
+// MARK: - Private
+
+private extension MainWindowStatusBarView {
+
+ func commonInit() {
+ heightAnchor.constraint(equalToConstant: Self.height).isActive = true
+
+ // A labeled group, so VoiceOver can find the bar and move through its controls.
+ setAccessibilityElement(true)
+ setAccessibilityRole(.group)
+ setAccessibilityLabel(NSLocalizedString("Status Bar", comment: "Main window status bar accessibility label"))
+
+ gearButton.delegate = self
+
+ progressIndicator.style = .bar
+ progressIndicator.controlSize = .small
+ progressIndicator.isIndeterminate = false
+ progressIndicator.isHidden = true
+ countLabel.isHidden = true
+
+ progressIndicator.addGestureRecognizer(NSClickGestureRecognizer(target: self, action: #selector(showActivityWindow(_:))))
+ countLabel.addGestureRecognizer(NSClickGestureRecognizer(target: self, action: #selector(countLabelClicked(_:))))
+
+ linkLabel.menu = makeLinkMenu()
+
+ splitHandleView.delegate = self
+ splitHandleView.isHidden = true
+
+ themePopUpButton.isBordered = false
+ themePopUpButton.controlSize = .small
+ themePopUpButton.font = NSFont.systemFont(ofSize: Self.fontSize)
+ let themeDescription = NSLocalizedString("Article Theme", comment: "Article Theme")
+ themePopUpButton.setAccessibilityLabel(themeDescription)
+ themePopUpButton.toolTip = themeDescription
+ updateThemePopUpButtonShadow()
+
+ // The split handle is added last so it’s on top: it straddles the left section’s edge.
+ for view in [gearButton, progressIndicator, countLabel, linkLabel, themePopUpButton, splitHandleView] {
+ addSubview(view)
+ }
+
+ addObservers()
+
+ updateCountLabel()
+ updateLinkLabel()
+ updateThemePopUpButton()
+ }
+
+ func addObservers() {
+ NotificationCenter.default.addObserver(self, selector: #selector(handleUnreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleUnreadCountDidChange(_:)), name: .UnreadCountDidInitialize, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleUnreadCountDisplaySettingDidChange(_:)), name: .unreadCountDisplaySettingDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleAccountChildrenDidChange(_:)), name: .ChildrenDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleAccountChildrenDidChange(_:)), name: .BatchUpdateDidPerform, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleAccountChildrenDidChange(_:)), name: .UserDidAddAccount, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleAccountChildrenDidChange(_:)), name: .UserDidDeleteAccount, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleAccountChildrenDidChange(_:)), name: .AccountStateDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleProgressInfoDidChange(_:)), name: .progressInfoDidChange, object: CombinedRefreshProgress.shared)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleCalendarDayChanged(_:)), name: .NSCalendarDayChanged, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleCurrentLocaleDidChange(_:)), name: NSLocale.currentLocaleDidChangeNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleSystemTimeZoneDidChange(_:)), name: .NSSystemTimeZoneDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThemeNamesDidChange(_:)), name: .ArticleThemeNamesDidChangeNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleCurrentArticleThemeDidChange(_:)), name: .CurrentArticleThemeDidChangeNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleUserDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil)
+ }
+
+ static func isDark(_ appearance: NSAppearance) -> Bool {
+ appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
+ }
+
+ static func dynamicColor(lightWhite: CGFloat, darkWhite: CGFloat) -> NSColor {
+ NSColor(name: nil) { appearance in
+ let white = isDark(appearance) ? darkWhite : lightWhite
+ return NSColor(srgbRed: white, green: white, blue: white, alpha: 1)
+ }
+ }
+
+ /// Etched text, as in the count and the link.
+ static func etchedString(_ string: String, font: NSFont, lineBreakMode: NSLineBreakMode) -> NSAttributedString {
+ let paragraphStyle = NSMutableParagraphStyle()
+ paragraphStyle.lineBreakMode = lineBreakMode
+ let attributes: [NSAttributedString.Key: Any] = [
+ .font: font,
+ .foregroundColor: textColor,
+ .shadow: etchedShadow,
+ .paragraphStyle: paragraphStyle
+ ]
+ return NSAttributedString(string: string, attributes: attributes)
+ }
+
+ /// Positions a view by its alignment rect — as Auto Layout would, so text fields’ built-in insets aren’t counted —
+ /// vertically centered in the content area and aligned to device pixels. Returns the alignment rect.
+ @discardableResult
+ func place(_ view: NSView, x: CGFloat, width: CGFloat, contentHeight: CGFloat) -> NSRect {
+ let height = view.intrinsicContentSize.height
+ let alignmentRect = NSRect(x: x, y: (contentHeight - height) / 2, width: max(width, 0), height: height)
+ view.frame = backingAlignedRect(view.frame(forAlignmentRect: alignmentRect), options: .alignAllEdgesNearest)
+ return alignmentRect
+ }
+
+ // MARK: - Count
+
+ @objc func updateCountLabel() {
+ let progressInfo = CombinedRefreshProgress.shared.progressInfo
+ progressIndicator.isHidden = progressInfo.isComplete
+
+ if progressInfo.isComplete {
+ setCountText(countText())
+ } else {
+ progressIndicator.maxValue = Double(progressInfo.numberOfTasks)
+ progressIndicator.doubleValue = Double(progressInfo.numberCompleted)
+ let formatString = NSLocalizedString("%@ of %@", comment: "Status bar progress")
+ setCountText(String(format: formatString, NSNumber(value: progressInfo.numberCompleted), NSNumber(value: progressInfo.numberOfTasks)))
+ }
+ needsLayout = true
+ }
+
+ func setCountText(_ text: String) {
+ let font = NSFont.monospacedDigitSystemFont(ofSize: Self.fontSize, weight: .regular)
+ countLabel.attributedStringValue = Self.etchedString(text, font: font, lineBreakMode: .byTruncatingTail)
+ }
+
+ static var showsUnreadCounts: Bool {
+ AppDefaults.unreadCountDisplay == .count
+ }
+
+ /// The saved mode, except that the unread count becomes the last refresh time when unread counts are hidden (hidden or a dot).
+ var effectiveCountMode: StatusBarCountMode {
+ let mode = AppDefaults.statusBarCountMode
+ if mode == .unreadCount && !Self.showsUnreadCounts {
+ return .lastRefresh
+ }
+ return mode
+ }
+
+ func countText() -> String {
+ switch effectiveCountMode {
+ case .lastRefresh:
+ guard let lastRefreshDate = AccountManager.shared.lastRefreshCompletedDate else {
+ return NSLocalizedString("Not updated yet", comment: "Status bar: no refresh has completed yet")
+ }
+ let formatString = NSLocalizedString("Updated %@", comment: "Updated")
+ return String(format: formatString, Self.lastRefreshDateString(lastRefreshDate))
+
+ case .unreadCount:
+ let formatString = NSLocalizedString("%d unread", comment: "Unread")
+ return String.localizedStringWithFormat(formatString, AccountManager.shared.unreadCount)
+
+ case .foldersAndFeeds:
+ let accounts = AccountManager.shared.activeAccounts
+ let folderCount = accounts.reduce(0) { $0 + ($1.folders?.count ?? 0) }
+ let feedCount = accounts.reduce(0) { $0 + $1.flattenedFeeds().count }
+ let attributedString = AttributedString(localized: "^[\(folderCount) folder](inflect: true), ^[\(feedCount) feed](inflect: true)", comment: "Status bar: number of folders and feeds")
+ return String(attributedString.characters)
+ }
+ }
+
+ /// Just the time when it’s today, otherwise the date and time — in the user’s locale.
+ static func lastRefreshDateString(_ date: Date) -> String {
+ if Calendar.current.isDateInToday(date) {
+ return date.formatted(date: .omitted, time: .shortened)
+ }
+ return date.formatted(date: .numeric, time: .shortened)
+ }
+
+ // MARK: - Link
+
+ /// The link’s contextual menu. Copy copies the whole link, with its scheme.
+ func makeLinkMenu() -> NSMenu {
+ let menu = NSMenu()
+ let copyItem = NSMenuItem(title: NSLocalizedString("Copy", comment: "Command"), action: #selector(copyLink(_:)), keyEquivalent: "")
+ copyItem.target = self
+ menu.addItem(copyItem)
+ return menu
+ }
+
+ func updateLinkLabel() {
+ guard let link, !link.isEmpty else {
+ linkLabel.stringValue = ""
+ linkLabel.toolTip = nil
+ return
+ }
+ let font = NSFont.systemFont(ofSize: Self.fontSize)
+ linkLabel.attributedStringValue = Self.etchedString(link.strippingHTTPOrHTTPSScheme, font: font, lineBreakMode: .byTruncatingMiddle)
+ linkLabel.toolTip = link
+ }
+
+ // MARK: - Theme
+
+ func updateThemePopUpButton() {
+ themePopUpButton.menu = ArticleThemesManager.shared.makeArticleThemeMenu()
+ themePopUpButton.selectItem(withTitle: ArticleThemesManager.shared.currentThemeName)
+ updateThemePopUpButtonVisibility()
+ }
+
+ /// Etches the pop-up button’s title and arrows. A view’s shadow doesn’t follow appearance changes, so it’s resolved here.
+ func updateThemePopUpButtonShadow() {
+ let shadow = NSShadow()
+ // A view’s shadow offset is in its own coordinates, and the pop-up button is flipped.
+ let offset = Self.etchedShadow.shadowOffset
+ shadow.shadowOffset = NSSize(width: offset.width, height: themePopUpButton.isFlipped ? -offset.height : offset.height)
+ shadow.shadowBlurRadius = Self.etchedShadow.shadowBlurRadius
+ effectiveAppearance.performAsCurrentDrawingAppearance {
+ if let cgColor = Self.etchedShadow.shadowColor?.cgColor {
+ shadow.shadowColor = NSColor(cgColor: cgColor)
+ }
+ }
+ themePopUpButton.shadow = shadow
+ }
+
+ func updateThemePopUpButtonVisibility() {
+ let isHidden = !AppDefaults.showStatusBarThemeMenu
+ guard themePopUpButton.isHidden != isHidden else {
+ return
+ }
+ themePopUpButton.isHidden = isHidden
+ needsLayout = true
+ }
+}
diff --git a/Mac/MainWindow/StatusBar/StatusBarGearButton.swift b/Mac/MainWindow/StatusBar/StatusBarGearButton.swift
new file mode 100644
index 000000000..1ffef9c3d
--- /dev/null
+++ b/Mac/MainWindow/StatusBar/StatusBarGearButton.swift
@@ -0,0 +1,100 @@
+//
+// StatusBarGearButton.swift
+// NetNewsWire
+//
+// Created by Brent Simmons on 10/12/26.
+// Copyright © 2026 Ranchero Software. All rights reserved.
+//
+
+import AppKit
+
+@MainActor protocol StatusBarGearButtonDelegate: AnyObject {
+ func gearButtonMenu(_ gearButton: StatusBarGearButton) -> NSMenu?
+}
+
+/// The gear-and-chevron button in the status bar. Clicking it pops up the delegate’s menu.
+final class StatusBarGearButton: NSView {
+
+ weak var delegate: StatusBarGearButtonDelegate?
+
+ private static let gearSymbolName = "gearshape.fill"
+ private static let chevronSymbolName = "chevron.down"
+ private static let gearPointSize: CGFloat = 12
+ private static let chevronPointSize: CGFloat = 7
+ private static let chevronSpacing: CGFloat = 2.5
+ private static let lightGray: CGFloat = 0.4
+ private static let darkGray: CGFloat = 0.65
+
+ private static let color = NSColor(name: nil) { appearance in
+ let isDark = appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
+ let white = isDark ? darkGray : lightGray
+ return NSColor(srgbRed: white, green: white, blue: white, alpha: 1)
+ }
+ private static let gearImage = symbolImage(gearSymbolName, pointSize: gearPointSize, weight: .regular)
+ private static let chevronImage = symbolImage(chevronSymbolName, pointSize: chevronPointSize, weight: .semibold)
+
+ override init(frame frameRect: NSRect) {
+ super.init(frame: frameRect)
+ commonInit()
+ }
+
+ required init?(coder: NSCoder) {
+ super.init(coder: coder)
+ commonInit()
+ }
+
+ override var intrinsicContentSize: NSSize {
+ let gearWidth = Self.gearImage?.size.width ?? 0
+ let chevronWidth = Self.chevronImage?.size.width ?? 0
+ return NSSize(width: ceil(gearWidth + Self.chevronSpacing + chevronWidth), height: NSView.noIntrinsicMetric)
+ }
+
+ override func draw(_ dirtyRect: NSRect) {
+ guard let gearImage = Self.gearImage, let chevronImage = Self.chevronImage else {
+ return
+ }
+ NSGraphicsContext.saveGraphicsState()
+ defer {
+ NSGraphicsContext.restoreGraphicsState()
+ }
+ MainWindowStatusBarView.etchedShadow.set()
+
+ let gearRect = NSRect(x: bounds.minX, y: floor(bounds.midY - gearImage.size.height / 2), width: gearImage.size.width, height: gearImage.size.height)
+ gearImage.draw(in: gearRect)
+ let chevronRect = NSRect(x: gearRect.maxX + Self.chevronSpacing, y: floor(bounds.midY - chevronImage.size.height / 2), width: chevronImage.size.width, height: chevronImage.size.height)
+ chevronImage.draw(in: chevronRect)
+ }
+
+ override func mouseDown(with event: NSEvent) {
+ popUpMenu()
+ }
+
+ override func accessibilityPerformPress() -> Bool {
+ popUpMenu()
+ }
+}
+
+private extension StatusBarGearButton {
+
+ func commonInit() {
+ let description = NSLocalizedString("Actions", comment: "Status bar gear menu accessibility label")
+ setAccessibilityElement(true)
+ setAccessibilityRole(.popUpButton)
+ setAccessibilityLabel(description)
+ toolTip = description
+ }
+
+ @discardableResult
+ func popUpMenu() -> Bool {
+ guard let menu = delegate?.gearButtonMenu(self) else {
+ return false
+ }
+ menu.popUp(positioning: nil, at: NSPoint(x: bounds.minX, y: bounds.minY), in: self)
+ return true
+ }
+
+ static func symbolImage(_ name: String, pointSize: CGFloat, weight: NSFont.Weight) -> NSImage? {
+ let configuration = NSImage.SymbolConfiguration(pointSize: pointSize, weight: weight).applying(NSImage.SymbolConfiguration(paletteColors: [color]))
+ return NSImage(systemSymbolName: name, accessibilityDescription: nil)?.withSymbolConfiguration(configuration)
+ }
+}
diff --git a/Mac/MainWindow/StatusBar/StatusBarSplitHandleView.swift b/Mac/MainWindow/StatusBar/StatusBarSplitHandleView.swift
new file mode 100644
index 000000000..5fbb80778
--- /dev/null
+++ b/Mac/MainWindow/StatusBar/StatusBarSplitHandleView.swift
@@ -0,0 +1,35 @@
+//
+// StatusBarSplitHandleView.swift
+// NetNewsWire
+//
+// Created by Brent Simmons on 10/11/26.
+// Copyright © 2026 Ranchero Software. All rights reserved.
+//
+
+import AppKit
+
+@MainActor protocol StatusBarSplitHandleViewDelegate: AnyObject {
+ func splitHandleView(_ splitHandleView: StatusBarSplitHandleView, didDragBy distance: CGFloat)
+ func splitHandleViewDidBeginDragging(_ splitHandleView: StatusBarSplitHandleView)
+}
+
+/// An invisible area in the status bar covering the ||| grip and the sidebar divider. Dragging it moves the divider.
+final class StatusBarSplitHandleView: NSView {
+
+ weak var delegate: StatusBarSplitHandleViewDelegate?
+
+ private var dragStartX: CGFloat = 0
+
+ override func resetCursorRects() {
+ addCursorRect(bounds, cursor: .columnResize)
+ }
+
+ override func mouseDown(with event: NSEvent) {
+ dragStartX = event.locationInWindow.x
+ delegate?.splitHandleViewDidBeginDragging(self)
+ }
+
+ override func mouseDragged(with event: NSEvent) {
+ delegate?.splitHandleView(self, didDragBy: event.locationInWindow.x - dragStartX)
+ }
+}
diff --git a/Mac/MainWindow/Timeline/Cell/ThumbnailView.swift b/Mac/MainWindow/Timeline/Cell/ThumbnailView.swift
new file mode 100644
index 000000000..2ec7698be
--- /dev/null
+++ b/Mac/MainWindow/Timeline/Cell/ThumbnailView.swift
@@ -0,0 +1,67 @@
+//
+// ThumbnailView.swift
+// NetNewsWire
+//
+// Created by Brent Simmons on 10/25/26.
+//
+
+import AppKit
+
+/// An article’s thumbnail in a timeline cell.
+///
+/// The whole image shows, scaled to fit. The cell sizes the view to the image, so the corner radius rounds the image itself.
+/// A placeholder color shows until the image arrives.
+final class ThumbnailView: NSView {
+
+ var image: NSImage? {
+ didSet {
+ if image !== oldValue {
+ needsDisplay = true
+ }
+ }
+ }
+
+ var cornerRadius: CGFloat = 0 {
+ didSet {
+ layer?.cornerRadius = cornerRadius
+ }
+ }
+
+ nonisolated override var isFlipped: Bool {
+ true
+ }
+
+ override var wantsUpdateLayer: Bool {
+ true
+ }
+
+ override init(frame frameRect: NSRect) {
+ super.init(frame: frameRect)
+ commonInit()
+ }
+
+ required init?(coder: NSCoder) {
+ super.init(coder: coder)
+ commonInit()
+ }
+
+ convenience init() {
+ self.init(frame: NSRect.zero)
+ }
+
+ override func updateLayer() {
+ layer?.contents = image?.cgImage(forProposedRect: nil, context: nil, hints: nil)
+ // Resolved here so the placeholder follows light and dark mode.
+ layer?.backgroundColor = image == nil ? Assets.Colors.thumbnailPlaceholder.cgColor : nil
+ }
+}
+
+private extension ThumbnailView {
+
+ func commonInit() {
+ wantsLayer = true
+ layerContentsRedrawPolicy = .onSetNeedsDisplay
+ layer?.contentsGravity = .resizeAspect
+ layer?.masksToBounds = true
+ }
+}
diff --git a/Mac/MainWindow/Timeline/Cell/TimelineCellAppearance.swift b/Mac/MainWindow/Timeline/Cell/TimelineCellAppearance.swift
index 457919e6c..498f19500 100644
--- a/Mac/MainWindow/Timeline/Cell/TimelineCellAppearance.swift
+++ b/Mac/MainWindow/Timeline/Cell/TimelineCellAppearance.swift
@@ -7,10 +7,12 @@
//
import AppKit
+import Images
struct TimelineCellAppearance: Equatable {
let showIcon: Bool
+ let showsLargeThumbnails: Bool
let cellPadding: NSEdgeInsets
@@ -19,9 +21,16 @@ struct TimelineCellAppearance: Equatable {
let dateFont: NSFont
let dateMarginLeft: CGFloat = 8.0
+ let feedNameAndDateAboveTitle: Bool
+ let feedNameAndDateBottomMargin: CGFloat = 2.0 // Above the title, when feedNameAndDateAboveTitle
+
let titleFont: NSFont
let titleBottomMargin: CGFloat = 1.0
- let titleNumberOfLines = 3
+ let numberOfLines: Int // Shared by the title and summary, or the title alone when there’s no summary
+ let showsSummary: Bool
+ let textOnlyNumberOfLines: Int // For the text when there’s no title
+ static let fullTitleMaximumNumberOfLines = 12
+ static let fullTitleTextOnlyMaximumNumberOfLines = 4
let textFont: NSFont
@@ -34,19 +43,26 @@ struct TimelineCellAppearance: Equatable {
let drawsGrid = false
- let iconSize = NSSize(width: 48, height: 48)
+ let iconSize: NSSize
let iconMarginLeft: CGFloat = 8.0
let iconMarginRight: CGFloat = 8.0
let iconAdjustmentTop: CGFloat = 4.0
let iconCornerRadius: CGFloat = 4.0
+ let thumbnailMaximumDimension: CGFloat = 76.0 // Smaller when the row is too short
+ let thumbnailMarginLeft: CGFloat = 8.0
+ let thumbnailCornerRadius: CGFloat = 4.0
+ let largeThumbnailMarginTop: CGFloat = 8.0
+ let largeThumbnailHeight: CGFloat = 180.0
+
let boxLeftMargin: CGFloat
- init(showIcon: Bool, fontSize: FontSize) {
+ /// With `showsFullTitles`, the title gets up to `fullTitleMaximumNumberOfLines` lines and there’s no summary.
+ /// An article with no title gets up to `fullTitleTextOnlyMaximumNumberOfLines` lines of text instead.
+ init(showIcon: Bool, textSize: TimelineTextSize, iconSize: IconSize, numberOfLines: Int, showsFullTitles: Bool, feedNameAndDateAboveTitle: Bool, showsLargeThumbnails: Bool) {
- let actualFontSize = AppDefaults.shared.actualFontSize(for: fontSize)
- let smallItemFontSize = floor(actualFontSize * 0.90)
- let largeItemFontSize = actualFontSize
+ let largeItemFontSize = textSize.pointSize
+ let smallItemFontSize = floor(largeItemFontSize * 0.90)
self.feedNameFont = NSFont.systemFont(ofSize: smallItemFontSize, weight: NSFont.Weight.bold)
self.dateFont = NSFont.systemFont(ofSize: smallItemFontSize, weight: NSFont.Weight.bold)
@@ -55,6 +71,12 @@ struct TimelineCellAppearance: Equatable {
self.textOnlyFont = NSFont.systemFont(ofSize: largeItemFontSize)
self.showIcon = showIcon
+ self.iconSize = iconSize.size
+ self.numberOfLines = showsFullTitles ? Self.fullTitleMaximumNumberOfLines : numberOfLines
+ self.showsSummary = !showsFullTitles
+ self.textOnlyNumberOfLines = showsFullTitles ? Self.fullTitleTextOnlyMaximumNumberOfLines : numberOfLines
+ self.feedNameAndDateAboveTitle = feedNameAndDateAboveTitle
+ self.showsLargeThumbnails = showsLargeThumbnails
cellPadding = NSEdgeInsets(top: 8.0, left: 4.0, bottom: 10.0, right: 4.0)
@@ -63,6 +85,30 @@ struct TimelineCellAppearance: Equatable {
}
}
+extension TimelineTextSize {
+
+ private static let smallPointSize: CGFloat = 12
+ private static let mediumPointSize: CGFloat = 14
+ private static let largePointSize: CGFloat = 16
+ private static let extraLargePointSize: CGFloat = 19
+ private static let extraExtraLargePointSize: CGFloat = 22
+
+ var pointSize: CGFloat {
+ switch self {
+ case .small:
+ Self.smallPointSize
+ case .medium:
+ Self.mediumPointSize
+ case .large:
+ Self.largePointSize
+ case .extraLarge:
+ Self.extraLargePointSize
+ case .extraExtraLarge:
+ Self.extraExtraLargePointSize
+ }
+ }
+}
+
extension NSEdgeInsets: @retroactive Equatable {
public static func ==(lhs: NSEdgeInsets, rhs: NSEdgeInsets) -> Bool {
diff --git a/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift b/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift
index 0e6665d22..61dc29a63 100644
--- a/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift
+++ b/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift
@@ -23,10 +23,12 @@ import Images
let showFeedName: TimelineShowFeedName
let iconImage: IconImage? // feed icon, user avatar, or favicon
let showIcon: Bool // Make space even when icon is nil
+ let thumbnail: NSImage?
+ let showThumbnail: Bool // Make space even when thumbnail is nil
let read: Bool
let starred: Bool
- init(article: Article, showFeedName: TimelineShowFeedName, feedName: String?, byline: String?, iconImage: IconImage?, showIcon: Bool) {
+ init(article: Article, showFeedName: TimelineShowFeedName, feedName: String?, byline: String?, iconImage: IconImage?, showIcon: Bool, thumbnail: NSImage?, showThumbnail: Bool) {
self.title = ArticleStringFormatter.shared.truncatedTitle(article)
self.attributedTitle = ArticleStringFormatter.shared.attributedTruncatedTitle(article)
@@ -40,10 +42,11 @@ import Images
self.feedName = ""
}
- if let byline = byline {
+ // Falls back to the feed name so the line is never empty.
+ if let byline, !byline.isEmpty {
self.byline = byline
} else {
- self.byline = ""
+ self.byline = self.feedName
}
self.showFeedName = showFeedName
@@ -51,6 +54,9 @@ import Images
self.showIcon = showIcon
self.iconImage = iconImage
+ self.thumbnail = thumbnail
+ self.showThumbnail = showThumbnail
+
self.read = article.status.read
self.starred = article.status.starred
}
@@ -73,6 +79,8 @@ import Images
self.showFeedName = .none
self.showIcon = false
self.iconImage = nil
+ self.thumbnail = nil
+ self.showThumbnail = false
self.read = true
self.starred = false
self.attributedTitle = NSAttributedString()
diff --git a/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift b/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift
index 3a2a70073..390891e9c 100644
--- a/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift
+++ b/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift
@@ -22,10 +22,11 @@ import RSCore
let unreadIndicatorRect: NSRect
let starRect: NSRect
let iconImageRect: NSRect
+ let thumbnailRect: NSRect
let separatorRect: NSRect
let paddingBottom: CGFloat
- init(width: CGFloat, height: CGFloat, feedNameRect: NSRect, dateRect: NSRect, titleRect: NSRect, numberOfLinesForTitle: Int, summaryRect: NSRect, textRect: NSRect, unreadIndicatorRect: NSRect, starRect: NSRect, iconImageRect: NSRect, separatorRect: NSRect, paddingBottom: CGFloat) {
+ init(width: CGFloat, height: CGFloat, feedNameRect: NSRect, dateRect: NSRect, titleRect: NSRect, numberOfLinesForTitle: Int, summaryRect: NSRect, textRect: NSRect, unreadIndicatorRect: NSRect, starRect: NSRect, iconImageRect: NSRect, thumbnailRect: NSRect, separatorRect: NSRect, paddingBottom: CGFloat) {
self.width = width
self.feedNameRect = feedNameRect
@@ -37,52 +38,69 @@ import RSCore
self.unreadIndicatorRect = unreadIndicatorRect
self.starRect = starRect
self.iconImageRect = iconImageRect
+ self.thumbnailRect = thumbnailRect
self.separatorRect = separatorRect
self.paddingBottom = paddingBottom
if height > 0.1 {
self.height = height
} else {
- self.height = [feedNameRect, dateRect, titleRect, summaryRect, textRect, unreadIndicatorRect, iconImageRect].maxY() + paddingBottom
+ self.height = [feedNameRect, dateRect, titleRect, summaryRect, textRect, unreadIndicatorRect, iconImageRect, thumbnailRect].maxY() + paddingBottom
}
}
- init(width: CGFloat, height: CGFloat, cellData: TimelineCellData, appearance: TimelineCellAppearance, hasIcon: Bool) {
+ init(width: CGFloat, height: CGFloat, cellData: TimelineCellData, appearance: TimelineCellAppearance) {
// If height == 0.0, then height is calculated.
let showIcon = cellData.showIcon
- var textBoxRect = TimelineCellLayout.rectForTextBox(appearance, cellData, showIcon, width)
- let (titleRect, numberOfLinesForTitle) = TimelineCellLayout.rectForTitle(textBoxRect, appearance, cellData)
- let summaryRect = numberOfLinesForTitle > 0 ? TimelineCellLayout.rectForSummary(textBoxRect, titleRect, numberOfLinesForTitle, appearance, cellData) : NSRect.zero
- let textRect = numberOfLinesForTitle > 0 ? NSRect.zero : TimelineCellLayout.rectForText(textBoxRect, appearance, cellData)
-
- var lastTextRect = titleRect
- if numberOfLinesForTitle == 0 {
- lastTextRect = textRect
- } else if numberOfLinesForTitle < appearance.titleNumberOfLines {
- if summaryRect.height > 0.1 {
- lastTextRect = summaryRect
- }
+ // When on top, the feed name and date line spans the small thumbnail too, and the thumbnail lines up with the title.
+ let textBoxRectWithoutThumbnail = TimelineCellLayout.rectForTextBox(appearance, cellData, showIcon, 0.0, width)
+ var dateRect = NSRect.zero
+ var bodyOriginY = textBoxRectWithoutThumbnail.minY
+ if appearance.feedNameAndDateAboveTitle {
+ dateRect = TimelineCellLayout.rectForDate(textBoxRectWithoutThumbnail, textBoxRectWithoutThumbnail.minY, appearance, cellData)
+ bodyOriginY = dateRect.maxY + appearance.feedNameAndDateBottomMargin
}
- let dateRect = TimelineCellLayout.rectForDate(textBoxRect, lastTextRect, appearance, cellData)
- let feedNameRect = TimelineCellLayout.rectForFeedName(textBoxRect, dateRect, appearance, cellData)
+
+ let thumbnailDimension = TimelineCellLayout.thumbnailDimension(cellData, appearance, bodyOriginY, height)
+ var textBoxRect = TimelineCellLayout.rectForTextBox(appearance, cellData, showIcon, thumbnailDimension, width)
+ var bodyRect = textBoxRect
+ bodyRect.origin.y = bodyOriginY
+
+ let (titleRect, numberOfLinesForTitle) = TimelineCellLayout.rectForTitle(bodyRect, appearance, cellData)
+ let summaryRect = numberOfLinesForTitle > 0 ? TimelineCellLayout.rectForSummary(bodyRect, titleRect, numberOfLinesForTitle, appearance, cellData) : NSRect.zero
+ let textRect = numberOfLinesForTitle > 0 ? NSRect.zero : TimelineCellLayout.rectForText(bodyRect, appearance, cellData)
+
+ if !appearance.feedNameAndDateAboveTitle {
+ var lastTextRect = titleRect
+ if numberOfLinesForTitle == 0 {
+ lastTextRect = textRect
+ } else if numberOfLinesForTitle < appearance.numberOfLines {
+ if summaryRect.height > 0.1 {
+ lastTextRect = summaryRect
+ }
+ }
+ dateRect = TimelineCellLayout.rectForDate(textBoxRect, lastTextRect.maxY + appearance.titleBottomMargin, appearance, cellData)
+ }
+ let feedNameRect = TimelineCellLayout.rectForFeedName(appearance.feedNameAndDateAboveTitle ? textBoxRectWithoutThumbnail : textBoxRect, dateRect, appearance, cellData)
textBoxRect.size.height = ceil([titleRect, summaryRect, textRect, dateRect, feedNameRect].maxY() - textBoxRect.origin.y)
let iconImageRect = TimelineCellLayout.rectForIcon(cellData, appearance, showIcon, textBoxRect, width, height)
- let unreadIndicatorRect = TimelineCellLayout.rectForUnreadIndicator(appearance, textBoxRect)
+ let thumbnailRect = appearance.showsLargeThumbnails ? TimelineCellLayout.rectForLargeThumbnail(cellData, appearance, textBoxRect, iconImageRect, width, height) : TimelineCellLayout.rectForThumbnail(appearance, thumbnailDimension, bodyOriginY, width)
+ let unreadIndicatorRect = TimelineCellLayout.rectForUnreadIndicator(appearance, textBoxRect, appearance.feedNameAndDateAboveTitle ? dateRect : nil)
let starRect = TimelineCellLayout.rectForStar(appearance, unreadIndicatorRect)
let separatorRect = TimelineCellLayout.rectForSeparator(cellData, appearance, showIcon ? iconImageRect : titleRect, width, height)
let paddingBottom = appearance.cellPadding.bottom
- self.init(width: width, height: height, feedNameRect: feedNameRect, dateRect: dateRect, titleRect: titleRect, numberOfLinesForTitle: numberOfLinesForTitle, summaryRect: summaryRect, textRect: textRect, unreadIndicatorRect: unreadIndicatorRect, starRect: starRect, iconImageRect: iconImageRect, separatorRect: separatorRect, paddingBottom: paddingBottom)
+ self.init(width: width, height: height, feedNameRect: feedNameRect, dateRect: dateRect, titleRect: titleRect, numberOfLinesForTitle: numberOfLinesForTitle, summaryRect: summaryRect, textRect: textRect, unreadIndicatorRect: unreadIndicatorRect, starRect: starRect, iconImageRect: iconImageRect, thumbnailRect: thumbnailRect, separatorRect: separatorRect, paddingBottom: paddingBottom)
}
static func height(for width: CGFloat, cellData: TimelineCellData, appearance: TimelineCellAppearance) -> CGFloat {
- let layout = TimelineCellLayout(width: width, height: 0.0, cellData: cellData, appearance: appearance, hasIcon: true)
+ let layout = TimelineCellLayout(width: width, height: 0.0, cellData: cellData, appearance: appearance)
return layout.height
}
}
@@ -91,13 +109,28 @@ import RSCore
@MainActor private extension TimelineCellLayout {
- static func rectForTextBox(_ appearance: TimelineCellAppearance, _ cellData: TimelineCellData, _ showIcon: Bool, _ width: CGFloat) -> NSRect {
+ /// The small right-side thumbnail’s width and height. Zero when there’s no small thumbnail.
+ /// A calculated height (zero) makes room for the full-size thumbnail.
+ /// Otherwise it fits between `originY` and the bottom padding, shrinking if the row is shorter than that.
+ static func thumbnailDimension(_ cellData: TimelineCellData, _ appearance: TimelineCellAppearance, _ originY: CGFloat, _ height: CGFloat) -> CGFloat {
+ guard cellData.showThumbnail, !appearance.showsLargeThumbnails else {
+ return 0.0
+ }
+ guard height > 0.1 else {
+ return appearance.thumbnailMaximumDimension
+ }
+ let availableHeight = floor(height - originY - appearance.cellPadding.bottom)
+ return max(0.0, min(appearance.thumbnailMaximumDimension, availableHeight))
+ }
+
+ static func rectForTextBox(_ appearance: TimelineCellAppearance, _ cellData: TimelineCellData, _ showIcon: Bool, _ thumbnailDimension: CGFloat, _ width: CGFloat) -> NSRect {
// Returned height is a placeholder. Not needed when this is calculated.
let iconSpace = showIcon ? appearance.iconSize.width + appearance.iconMarginRight : 0.0
+ let thumbnailSpace = thumbnailDimension > 0.0 ? thumbnailDimension + appearance.thumbnailMarginLeft : 0.0
let textBoxOriginX = appearance.cellPadding.left + appearance.unreadCircleDimension + appearance.unreadCircleMarginRight + iconSpace
- let textBoxMaxX = floor(width - appearance.cellPadding.right)
+ let textBoxMaxX = floor(width - appearance.cellPadding.right - thumbnailSpace)
let textBoxWidth = floor(textBoxMaxX - textBoxOriginX)
let textBoxRect = NSRect(x: textBoxOriginX, y: appearance.cellPadding.top, width: textBoxWidth, height: 1000000)
@@ -114,7 +147,7 @@ import RSCore
}
let attributedTitle = cellData.attributedTitle.applyingBaseFont(appearance.titleFont)
- let sizeInfo = MultilineTextFieldSizer.size(for: attributedTitle, numberOfLines: appearance.titleNumberOfLines, width: Int(textBoxRect.width))
+ let sizeInfo = MultilineTextFieldSizer.size(for: attributedTitle, numberOfLines: appearance.numberOfLines, width: Int(textBoxRect.width))
r.size.height = sizeInfo.size.height
if sizeInfo.numberOfLinesUsed < 1 {
r.size.height = 0
@@ -123,13 +156,13 @@ import RSCore
}
static func rectForSummary(_ textBoxRect: NSRect, _ titleRect: NSRect, _ titleNumberOfLines: Int, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect {
- if titleNumberOfLines >= appearance.titleNumberOfLines || cellData.text.isEmpty {
+ if !appearance.showsSummary || titleNumberOfLines >= appearance.numberOfLines || cellData.text.isEmpty {
return NSRect.zero
}
var r = textBoxRect
r.origin.y = titleRect.maxY
- let summaryNumberOfLines = appearance.titleNumberOfLines - titleNumberOfLines
+ let summaryNumberOfLines = appearance.numberOfLines - titleNumberOfLines
let sizeInfo = MultilineTextFieldSizer.size(for: cellData.text, font: appearance.textOnlyFont, numberOfLines: summaryNumberOfLines, width: Int(textBoxRect.width))
r.size.height = sizeInfo.size.height
@@ -148,7 +181,7 @@ import RSCore
return r
}
- let sizeInfo = MultilineTextFieldSizer.size(for: cellData.text, font: appearance.textOnlyFont, numberOfLines: appearance.titleNumberOfLines, width: Int(textBoxRect.width))
+ let sizeInfo = MultilineTextFieldSizer.size(for: cellData.text, font: appearance.textOnlyFont, numberOfLines: appearance.textOnlyNumberOfLines, width: Int(textBoxRect.width))
r.size.height = sizeInfo.size.height
if sizeInfo.numberOfLinesUsed < 1 {
r.size.height = 0
@@ -156,12 +189,12 @@ import RSCore
return r
}
- static func rectForDate(_ textBoxRect: NSRect, _ rectAbove: NSRect, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect {
+ static func rectForDate(_ textBoxRect: NSRect, _ originY: CGFloat, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect {
let textFieldSize = SingleLineTextFieldSizer.size(for: cellData.dateString, font: appearance.dateFont)
var r = NSRect.zero
r.size = textFieldSize
- r.origin.y = rectAbove.maxY + appearance.titleBottomMargin
+ r.origin.y = originY
r.size.width = textFieldSize.width
r.origin.x = textBoxRect.maxX - textFieldSize.width
@@ -184,12 +217,17 @@ import RSCore
return r
}
- static func rectForUnreadIndicator(_ appearance: TimelineCellAppearance, _ titleRect: NSRect) -> NSRect {
+ /// Lines up with the title’s first line, or is centered on `firstLineRect` when the feed name and date line is on top.
+ static func rectForUnreadIndicator(_ appearance: TimelineCellAppearance, _ titleRect: NSRect, _ firstLineRect: NSRect?) -> NSRect {
var r = NSRect.zero
r.size = NSSize(width: appearance.unreadCircleDimension, height: appearance.unreadCircleDimension)
r.origin.x = appearance.cellPadding.left
- r.origin.y = titleRect.minY + 6
+ if let firstLineRect {
+ r.origin.y = floor(firstLineRect.midY - (appearance.unreadCircleDimension / 2.0))
+ } else {
+ r.origin.y = titleRect.minY + 6
+ }
// r = RSRectCenteredVerticallyInRect(r, titleRect)
// r.origin.y += 1
@@ -219,6 +257,41 @@ import RSCore
return r
}
+ static func rectForThumbnail(_ appearance: TimelineCellAppearance, _ thumbnailDimension: CGFloat, _ originY: CGFloat, _ width: CGFloat) -> NSRect {
+ if thumbnailDimension <= 0.0 {
+ return NSRect.zero
+ }
+ let originX = floor(width - appearance.cellPadding.right - thumbnailDimension)
+ return NSRect(x: originX, y: originY, width: thumbnailDimension, height: thumbnailDimension)
+ }
+
+ /// Below the text and icon, `largeThumbnailHeight` tall, from the icon’s left edge
+ /// (or the text’s, when there’s no icon) to the right padding.
+ /// In a cell, it’s bottom-aligned, and it shrinks rather than overlap the text
+ /// if the row is shorter than its calculated height, as when its height is still an estimate.
+ static func rectForLargeThumbnail(_ cellData: TimelineCellData, _ appearance: TimelineCellAppearance, _ textBoxRect: NSRect, _ iconImageRect: NSRect, _ width: CGFloat, _ height: CGFloat) -> NSRect {
+ guard cellData.showThumbnail else {
+ return NSRect.zero
+ }
+
+ let originX = cellData.showIcon ? iconImageRect.minX : textBoxRect.minX
+ let thumbnailWidth = floor(width - appearance.cellPadding.right - originX)
+ var thumbnailHeight = appearance.largeThumbnailHeight
+ let minimumOriginY = ceil(max(textBoxRect.maxY, iconImageRect.maxY) + appearance.largeThumbnailMarginTop)
+ var originY = minimumOriginY
+
+ if height > 0.1 {
+ let maximumY = floor(height - appearance.cellPadding.bottom)
+ thumbnailHeight = min(thumbnailHeight, maximumY - minimumOriginY)
+ originY = maximumY - thumbnailHeight
+ }
+
+ guard thumbnailWidth > 0.0, thumbnailHeight > 0.0 else {
+ return NSRect.zero
+ }
+ return NSRect(x: originX, y: originY, width: thumbnailWidth, height: thumbnailHeight)
+ }
+
static func rectForSeparator(_ cellData: TimelineCellData, _ appearance: TimelineCellAppearance, _ alignmentRect: NSRect, _ width: CGFloat, _ height: CGFloat) -> NSRect {
return NSRect(x: alignmentRect.minX, y: height - 1, width: width - alignmentRect.minX, height: 1)
}
diff --git a/Mac/MainWindow/Timeline/Cell/TimelineColumnCellViews.swift b/Mac/MainWindow/Timeline/Cell/TimelineColumnCellViews.swift
index 1754adcde..682476ee6 100644
--- a/Mac/MainWindow/Timeline/Cell/TimelineColumnCellViews.swift
+++ b/Mac/MainWindow/Timeline/Cell/TimelineColumnCellViews.swift
@@ -125,6 +125,21 @@ final class TimelineTextColumnCellView: NSTableCellView {
/// Feed icon plus feed name.
final class TimelineFeedColumnCellView: NSTableCellView {
+ /// When false, the icon is hidden and the name starts at the leading edge.
+ var showsIcon = true {
+ didSet {
+ guard showsIcon != oldValue else {
+ return
+ }
+ imageView?.isHidden = !showsIcon
+ labelLeadingAfterIconConstraint?.isActive = showsIcon
+ labelLeadingWithoutIconConstraint?.isActive = !showsIcon
+ }
+ }
+
+ private var labelLeadingAfterIconConstraint: NSLayoutConstraint?
+ private var labelLeadingWithoutIconConstraint: NSLayoutConstraint?
+
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
let iconView = NSImageView()
@@ -140,12 +155,16 @@ final class TimelineFeedColumnCellView: NSTableCellView {
addSubview(label)
textField = label
+ let labelLeadingAfterIconConstraint = label.leadingAnchor.constraint(equalTo: iconView.trailingAnchor, constant: feedIconMarginRight)
+ self.labelLeadingAfterIconConstraint = labelLeadingAfterIconConstraint
+ self.labelLeadingWithoutIconConstraint = label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: columnCellHorizontalPadding)
+
NSLayoutConstraint.activate([
iconView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: columnCellHorizontalPadding),
iconView.widthAnchor.constraint(equalToConstant: feedIconDimension),
iconView.heightAnchor.constraint(equalToConstant: feedIconDimension),
iconView.centerYAnchor.constraint(equalTo: centerYAnchor),
- label.leadingAnchor.constraint(equalTo: iconView.trailingAnchor, constant: feedIconMarginRight),
+ labelLeadingAfterIconConstraint,
label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -columnCellHorizontalPadding),
label.centerYAnchor.constraint(equalTo: centerYAnchor)
])
diff --git a/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift b/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift
index 9fd5a1766..1788444a6 100644
--- a/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift
+++ b/Mac/MainWindow/Timeline/Cell/TimelineTableCellView.swift
@@ -19,6 +19,7 @@ final class TimelineTableCellView: NSTableCellView {
private let feedNameView = TimelineTableCellView.singleLineTextField()
private lazy var iconView = IconView()
+ private let thumbnailView = ThumbnailView()
private var starView = TimelineTableCellView.imageView(with: Assets.Images.timelineStar, scaling: .scaleNone)
@@ -31,6 +32,7 @@ final class TimelineTableCellView: NSTableCellView {
if cellAppearance != oldValue {
updateTextFieldFonts()
iconView.layer?.cornerRadius = cellAppearance.iconCornerRadius
+ thumbnailView.cornerRadius = cellAppearance.thumbnailCornerRadius
needsLayout = true
}
}
@@ -42,6 +44,16 @@ final class TimelineTableCellView: NSTableCellView {
}
}
+ /// The image shown now, which can be newer than `cellData.thumbnail`. Setting this leaves the rest of the cell as it is.
+ var thumbnail: NSImage? {
+ get {
+ thumbnailView.image
+ }
+ set {
+ setThumbnailImage(newValue)
+ }
+ }
+
var isEmphasized: Bool = false {
didSet {
unreadIndicatorView.isEmphasized = isEmphasized
@@ -106,6 +118,8 @@ final class TimelineTableCellView: NSTableCellView {
unreadIndicatorView.setFrameIfNotEqual(layoutRects.unreadIndicatorRect)
feedNameView.setFrameIfNotEqual(layoutRects.feedNameRect)
iconView.setFrameIfNotEqual(layoutRects.iconImageRect)
+ // Sized to the image, so the corner radius rounds the image itself. All of the rect until the image arrives.
+ thumbnailView.setFrameIfNotEqual(layoutRects.thumbnailRect.aspectFitRect(for: thumbnailView.image?.size ?? .zero))
starView.setFrameIfNotEqual(layoutRects.starRect)
}
}
@@ -187,6 +201,7 @@ private extension TimelineTableCellView {
addSubviewAtInit(dateView, hidden: false)
addSubviewAtInit(feedNameView, hidden: true)
addSubviewAtInit(iconView, hidden: true)
+ addSubviewAtInit(thumbnailView, hidden: true)
addSubviewAtInit(starView, hidden: true)
makeTextFieldColorsNormal()
@@ -194,7 +209,7 @@ private extension TimelineTableCellView {
func updatedLayoutRects() -> TimelineCellLayout {
- return TimelineCellLayout(width: bounds.width, height: bounds.height, cellData: cellData, appearance: cellAppearance, hasIcon: iconView.iconImage != nil)
+ return TimelineCellLayout(width: bounds.width, height: bounds.height, cellData: cellData, appearance: cellAppearance)
}
func updateTitleView() {
@@ -282,6 +297,35 @@ private extension TimelineTableCellView {
hideView(iconView)
}
+ func updateThumbnail() {
+ guard cellData.showThumbnail else {
+ makeThumbnailEmpty()
+ return
+ }
+
+ if thumbnailView.isHidden {
+ showView(thumbnailView)
+ needsLayout = true
+ }
+ setThumbnailImage(cellData.thumbnail)
+ }
+
+ func makeThumbnailEmpty() {
+ if !thumbnailView.isHidden {
+ hideView(thumbnailView)
+ needsLayout = true
+ }
+ setThumbnailImage(nil)
+ }
+
+ /// Lays out again, since the thumbnail view is sized to the image.
+ func setThumbnailImage(_ image: NSImage?) {
+ if thumbnailView.image !== image {
+ thumbnailView.image = image
+ needsLayout = true
+ }
+ }
+
func hideView(_ view: NSView) {
if !view.isHidden {
view.isHidden = true
@@ -311,5 +355,6 @@ private extension TimelineTableCellView {
updateUnreadIndicator()
updateStarView()
updateIcon()
+ updateThumbnail()
}
}
diff --git a/Mac/MainWindow/Timeline/TimelineContainerViewController.swift b/Mac/MainWindow/Timeline/TimelineContainerViewController.swift
index eba9c5991..0fd082318 100644
--- a/Mac/MainWindow/Timeline/TimelineContainerViewController.swift
+++ b/Mac/MainWindow/Timeline/TimelineContainerViewController.swift
@@ -24,7 +24,7 @@ final class TimelineContainerViewController: NSViewController {
@IBOutlet var containerViewTopToHeaderConstraint: NSLayoutConstraint?
@IBOutlet var containerView: TimelineContainerView!
- private var layout = AppDefaults.shared.timelineLayout {
+ private var layout = AppDefaults.timelineLayout {
didSet {
if layout != oldValue {
layoutDidChange()
@@ -116,7 +116,7 @@ final class TimelineContainerViewController: NSViewController {
}
private func userDefaultsDidChange() {
- layout = AppDefaults.shared.timelineLayout
+ layout = AppDefaults.timelineLayout
}
// MARK: - API
@@ -254,10 +254,10 @@ private extension TimelineContainerViewController {
/// For a window with no saved sort. Group By Feed, from before sorting was per window, became sorting by feed.
static var seedSortParameters: ArticleSortParameters {
- if AppDefaults.shared.timelineGroupByFeed {
+ if AppDefaults.timelineGroupByFeed {
return ArticleSortParameters(key: .feed, direction: .orderedAscending)
}
- return ArticleSortParameters(key: .date, direction: AppDefaults.shared.timelineSortDirection)
+ return ArticleSortParameters(key: .date, direction: AppDefaults.timelineSortDirection)
}
func layoutDidChange() {
diff --git a/Mac/MainWindow/Timeline/TimelineLayout.swift b/Mac/MainWindow/Timeline/TimelineLayout.swift
index e8eafeb11..ac4c90860 100644
--- a/Mac/MainWindow/Timeline/TimelineLayout.swift
+++ b/Mac/MainWindow/Timeline/TimelineLayout.swift
@@ -17,7 +17,7 @@ enum TimelineLayout {
extension AppDefaults {
- var timelineLayout: TimelineLayout {
+ static var timelineLayout: TimelineLayout {
useColumnLayout ? .column : .standard
}
}
diff --git a/Mac/MainWindow/Timeline/TimelineTableRowView.swift b/Mac/MainWindow/Timeline/TimelineTableRowView.swift
index 3f7fb8cfa..bc4c739a8 100644
--- a/Mac/MainWindow/Timeline/TimelineTableRowView.swift
+++ b/Mac/MainWindow/Timeline/TimelineTableRowView.swift
@@ -10,7 +10,18 @@ import AppKit
final class TimelineTableRowView: NSTableRowView {
- private var separator: NSView?
+ /// The last row has no separator below it.
+ var isLastRow = false {
+ didSet {
+ if isLastRow != oldValue {
+ needsDisplay = true
+ }
+ }
+ }
+
+ private static let separatorInsetLeft: CGFloat = 20.0
+ private static let separatorInsetRight: CGFloat = 4.0
+ private static let separatorHeight: CGFloat = 1.0
override var isOpaque: Bool {
return true
@@ -25,7 +36,6 @@ final class TimelineTableRowView: NSTableRowView {
override var isSelected: Bool {
didSet {
cellView?.isSelected = isSelected
- separator?.isHidden = isSelected
}
}
@@ -46,25 +56,14 @@ final class TimelineTableRowView: NSTableRowView {
return nil
}
- override func viewDidMoveToSuperview() {
- if AppDefaults.shared.timelineShowsSeparators {
- addSeparatorView()
+ /// Called only when the table’s `gridStyleMask` includes horizontal lines. Inset to line up with the cell’s content.
+ override func drawSeparator(in dirtyRect: NSRect) {
+ guard !isLastRow, !isSelected, let cellView else {
+ return
}
+ let separatorRect = NSRect(x: cellView.frame.minX + Self.separatorInsetLeft, y: bounds.maxY - Self.separatorHeight, width: cellView.frame.width - Self.separatorInsetLeft - Self.separatorInsetRight, height: Self.separatorHeight)
+ let gridColor = (superview as? NSTableView)?.gridColor ?? .gridColor
+ gridColor.setFill()
+ separatorRect.fill(using: .sourceOver)
}
-
- private func addSeparatorView() {
- guard let cellView = cellView, separator == nil else { return }
- separator = NSView()
- separator!.translatesAutoresizingMaskIntoConstraints = false
- separator!.wantsLayer = true
- separator!.layer?.backgroundColor = Assets.Colors.timelineSeparator.cgColor
- addSubview(separator!)
- NSLayoutConstraint.activate([
- separator!.leadingAnchor.constraint(equalTo: cellView.leadingAnchor, constant: 20),
- separator!.trailingAnchor.constraint(equalTo: cellView.trailingAnchor, constant: -4),
- separator!.heightAnchor.constraint(equalToConstant: 1),
- separator!.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0)
- ])
- }
-
}
diff --git a/Mac/MainWindow/Timeline/TimelineTableView.swift b/Mac/MainWindow/Timeline/TimelineTableView.swift
index 33f032cbf..632c1ac22 100644
--- a/Mac/MainWindow/Timeline/TimelineTableView.swift
+++ b/Mac/MainWindow/Timeline/TimelineTableView.swift
@@ -9,9 +9,16 @@
import AppKit
import RSCore
+/// Measures row heights for rows about to be shown, so they draw at their measured heights.
+@MainActor protocol TimelineTableViewRowHeightDelegate: AnyObject {
+ func timelineTableViewDidLayout(_ tableView: TimelineTableView)
+ func timelineTableViewDidEndLiveResize(_ tableView: TimelineTableView)
+}
+
final class TimelineTableView: NSTableView {
weak var keyboardDelegate: KeyboardDelegate?
+ weak var rowHeightDelegate: TimelineTableViewRowHeightDelegate?
override func accessibilityLabel() -> String? {
return NSLocalizedString("Timeline", comment: "Timeline")
@@ -31,4 +38,14 @@ final class TimelineTableView: NSTableView {
override var isOpaque: Bool {
return true
}
+
+ override func layout() {
+ super.layout()
+ rowHeightDelegate?.timelineTableViewDidLayout(self)
+ }
+
+ override func viewDidEndLiveResize() {
+ super.viewDidEndLiveResize()
+ rowHeightDelegate?.timelineTableViewDidEndLiveResize(self)
+ }
}
diff --git a/Mac/MainWindow/Timeline/TimelineViewController+ColumnLayout.swift b/Mac/MainWindow/Timeline/TimelineViewController+ColumnLayout.swift
index f7ef2326c..7cc7a5e10 100644
--- a/Mac/MainWindow/Timeline/TimelineViewController+ColumnLayout.swift
+++ b/Mac/MainWindow/Timeline/TimelineViewController+ColumnLayout.swift
@@ -27,12 +27,12 @@ extension TimelineViewController {
}
var columnFont: NSFont {
- NSFont.systemFont(ofSize: AppDefaults.shared.actualFontSize(for: AppDefaults.shared.timelineFontSize))
+ NSFont.systemFont(ofSize: AppDefaults.timelineTextSize.pointSize)
}
// Unread rows are bold, like Mail.
var boldColumnFont: NSFont {
- NSFont.boldSystemFont(ofSize: AppDefaults.shared.actualFontSize(for: AppDefaults.shared.timelineFontSize))
+ NSFont.boldSystemFont(ofSize: AppDefaults.timelineTextSize.pointSize)
}
func columnRowHeight() -> CGFloat {
@@ -71,7 +71,8 @@ extension TimelineViewController {
let cell = dequeueCell(TimelineFeedColumnCellView.self, identifier: identifier)
cell.textField?.font = textFont
cell.textField?.stringValue = article?.feed?.nameForDisplay ?? ""
- cell.imageView?.image = article?.feed.flatMap { IconImageCache.shared.imageForFeed($0) }?.image
+ cell.showsIcon = showIcons
+ cell.imageView?.image = showIcons ? article?.feed.flatMap { IconImageCache.shared.imageForFeed($0) }?.image : nil
return cell
case .date:
diff --git a/Mac/MainWindow/Timeline/TimelineViewController.swift b/Mac/MainWindow/Timeline/TimelineViewController.swift
index 334c45996..803a9fe05 100644
--- a/Mac/MainWindow/Timeline/TimelineViewController.swift
+++ b/Mac/MainWindow/Timeline/TimelineViewController.swift
@@ -12,6 +12,7 @@ import Articles
import Account
import os
import Images
+import RSWeb
@MainActor protocol TimelineDelegate: AnyObject {
func timelineSelectionDidChange(_: TimelineViewController, selectedArticles: [Article]?)
@@ -132,26 +133,24 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
// but some data in some of the articles may have changed.
// Just reload visible cells in this case: don’t call reloadData.
articleRowMap = [String: [Int]]()
+ remeasureRowHeights(rowsWithChangedArticles(comparedWith: oldValue))
reloadVisibleCells()
return
}
- if let representedObjects = representedObjects, representedObjects.count == 1 && representedObjects.first is Feed {
- showFeedNames = {
- for article in articles {
- if !article.byline().isEmpty {
- return .byline
- }
- }
- return .none
- }()
+ if let representedObjects, representedObjects.count == 1 && representedObjects.first is Feed {
+ showFeedNames = .byline
} else {
showFeedNames = .feed
}
+ updateShowIcons() // Automatic depends on these articles’ author avatars, even when showFeedNames didn’t change
articleRowMap = [String: [Int]]()
+ removeRowHeightsForMissingArticles()
tableView.reloadData()
- IconImageCache.shared.prefetchImagesForArticles(articles)
+ if showIcons {
+ IconImageCache.shared.prefetchImagesForArticles(articles)
+ }
}
}
@@ -174,6 +173,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
private var showFeedNames: TimelineShowFeedName = .none {
didSet {
if showFeedNames != oldValue {
+ rowHeights.removeAll()
updateShowIcons()
updateTableViewRowHeight()
reloadVisibleCells()
@@ -181,8 +181,34 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
}
}
- private var showIcons = false
- private var currentRowHeight: CGFloat = 0.0
+ private(set) var showIcons = false {
+ didSet {
+ if showIcons != oldValue {
+ rowHeights.removeAll()
+ }
+ }
+ }
+ private var estimatedRowHeight: CGFloat = 0.0 // For rows not yet measured
+ private var rowHeights = [ArticleIdentityKey: TimelineRowHeight]() // Height measured at rowHeightWidth
+ private var rowHeightWidth: CGFloat = 0.0 // The width of a standard-layout cell
+ private var rowHeightMeasuringStartRow: Int? // Where the next measuring pass starts
+ private var isRowHeightMeasuringScheduled = false
+ private static let rowHeightBatchSize = 500
+ private var thumbnailsDisplay = AppDefaults.timelineThumbnailsDisplay {
+ didSet {
+ if thumbnailsDisplay != oldValue {
+ thumbnailsDisplayDidChange()
+ }
+ }
+ }
+
+ /// Narrow enough that the prototype’s title uses every line.
+ private static let prototypeRowWidth: CGFloat = 100.0
+
+ /// Nil when the timeline doesn’t show thumbnails. Column layout never shows them.
+ private var thumbnailMode: ThumbnailMode? {
+ layout == .standard ? thumbnailsDisplay.thumbnailMode : nil
+ }
private var didRegisterForNotifications = false
static let fetchAndMergeArticlesQueue = CoalescingQueue(name: "Fetch and Merge Articles", interval: 0.5, maxInterval: 2.0)
@@ -209,17 +235,59 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
var standardColumn: NSTableColumn?
// Set while columns are added and autosaved state is restored, which fires sortDescriptorsDidChange.
var isConfiguringTableColumns = false
- private var fontSize: FontSize = AppDefaults.shared.timelineFontSize {
+ private var textSize = AppDefaults.timelineTextSize {
didSet {
- if fontSize != oldValue {
- fontSizeDidChange()
+ if textSize != oldValue {
+ cellAppearanceSettingDidChange()
}
}
}
+ private var numberOfLines = AppDefaults.timelineNumberOfLines {
+ didSet {
+ if numberOfLines != oldValue {
+ cellAppearanceSettingDidChange()
+ }
+ }
+ }
+ private var showFullTitles = AppDefaults.timelineShowFullTitles {
+ didSet {
+ if showFullTitles != oldValue {
+ cellAppearanceSettingDidChange()
+ }
+ }
+ }
+ private var feedNameAndDateAboveTitle = AppDefaults.timelineFeedNameAndDateAboveTitle {
+ didSet {
+ if feedNameAndDateAboveTitle != oldValue {
+ cellAppearanceSettingDidChange()
+ }
+ }
+ }
+ private var fadesReadArticles = AppDefaults.timelineFadeReadArticles {
+ didSet {
+ if fadesReadArticles != oldValue {
+ reloadVisibleCells()
+ }
+ }
+ }
+ private static let readArticleAlphaValue: CGFloat = 0.6
- private struct ArticleIdentityKey: Equatable {
+ /// Two accounts can have articles with the same articleID — the same feed in On My Mac and iCloud, for instance.
+ private struct ArticleIdentityKey: Hashable {
let accountID: String
let articleID: String
+
+ init(_ article: Article) {
+ self.accountID = article.accountID
+ self.articleID = article.articleID
+ }
+ }
+
+ /// A changed article is a new instance, so `article` tells whether the height is still current.
+ private struct TimelineRowHeight {
+ let article: Article
+ let showsThumbnail: Bool
+ let height: CGFloat
}
private var previouslySelectedArticleKeys: [ArticleIdentityKey]?
@@ -229,7 +297,6 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
}
private let keyboardDelegate = TimelineKeyboardDelegate()
- private var timelineShowsSeparatorsObserver: NSKeyValueObservation?
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "TimelineViewController")
@@ -239,36 +306,53 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
}
override func viewDidLoad() {
- cellAppearance = TimelineCellAppearance(showIcon: false, fontSize: fontSize)
- cellAppearanceWithIcon = TimelineCellAppearance(showIcon: true, fontSize: fontSize)
+ // The search timeline can be created long before its view loads, and defaults are observed only from here on.
+ textSize = AppDefaults.timelineTextSize
+ numberOfLines = AppDefaults.timelineNumberOfLines
+ showFullTitles = AppDefaults.timelineShowFullTitles
+ feedNameAndDateAboveTitle = AppDefaults.timelineFeedNameAndDateAboveTitle
+ fadesReadArticles = AppDefaults.timelineFadeReadArticles
+ updateGridStyle()
+ thumbnailsDisplay = AppDefaults.timelineThumbnailsDisplay
+ updateCellAppearances()
- updateRowHeights()
+ updateEstimatedRowHeight()
tableView.target = self
tableView.doubleAction = #selector(openArticleInBrowser(_:))
tableView.setDraggingSourceOperationMask(.copy, forLocal: false)
tableView.keyboardDelegate = keyboardDelegate
+ tableView.rowHeightDelegate = self
tableView.style = .inset
+ tableView.gridColor = .separatorColor
standardColumn = tableView.tableColumns.first
configureTableView(for: layout)
+ updateGridStyle()
updateShowIcons()
if !didRegisterForNotifications {
NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil)
- 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(handleFeedIconImageDidChange(_:)), name: .feedIconImageDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleAuthorAvatarImageDidChange(_:)), name: .authorAvatarImageDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleGrayscaleIconsDidChange(_:)), name: .grayscaleIconsDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleThumbnailDidBecomeAvailable(_:)), name: .thumbnailDidBecomeAvailable, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThumbnailDownloadDidFail(_:)), name: .articleThumbnailDownloadDidFail, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleNetworkStatusDidChange(_:)), name: .networkStatusDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountDidDownloadArticles(_:)), name: .AccountDidDownloadArticles, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountStateDidChange(_:)), name: .AccountStateDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidAddAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDidDeleteAccount(_:)), name: .UserDidDeleteAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleSidebarDidAcceptDrop(_:)), name: .SidebarDidAcceptDrop, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(containerChildrenDidChange(_:)), name: .ChildrenDidChange, 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(handleTimelineShowSeparatorsDidChange(_:)), name: .timelineShowSeparatorsDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineThumbnailsDisplayDidChange(_:)), name: .timelineThumbnailsDisplayDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFeedIconsDisplayDidChange(_:)), name: .timelineFeedIconsDisplayDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineIconSizeDidChange(_:)), name: .timelineIconSizeDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineTextSizeDidChange(_:)), name: .timelineTextSizeDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineNumberOfLinesDidChange(_:)), name: .timelineNumberOfLinesDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineShowFullTitlesDidChange(_:)), name: .timelineShowFullTitlesDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFeedNameAndDateAboveTitleDidChange(_:)), name: .timelineFeedNameAndDateAboveTitleDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFadeReadArticlesDidChange(_:)), name: .timelineFadeReadArticlesDidChange, object: nil)
didRegisterForNotifications = true
}
@@ -279,6 +363,11 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
sharingServiceDelegate = SharingServiceDelegate(self.view.window)
}
+ override func viewDidLayout() {
+ super.viewDidLayout()
+ fitTableViewToVisibleWidthInStandardLayout()
+ }
+
// MARK: - API
func markAllAsRead(completion: (() -> Void)? = nil) {
@@ -459,13 +548,11 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
tableView.selectRow(nextRowIndex)
- let followingRowIndex = nextRowIndex - 1
- if followingRowIndex < 0 {
+ if scrollToRowIfNotFullyVisible(nextRowIndex) {
return
}
- tableView.scrollToRowIfNotVisible(followingRowIndex)
-
+ scrollToRowIfNotFullyVisible(nextRowIndex - 1)
}
@IBAction func selectNextDown(_ sender: Any?) {
@@ -481,13 +568,11 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
tableView.selectRow(nextRowIndex)
- let followingRowIndex = nextRowIndex + 1
- if followingRowIndex > tableMaxIndex {
+ if scrollToRowIfNotFullyVisible(nextRowIndex) {
return
}
- tableView.scrollToRowIfNotVisible(followingRowIndex)
-
+ scrollToRowIfNotFullyVisible(nextRowIndex + 1)
}
func toggleReadStatusForSelectedArticles() {
@@ -678,8 +763,8 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
updateUnreadCount()
}
- @objc func feedIconDidBecomeAvailable(_ note: Notification) {
- guard showIcons, let feed = note.userInfo?[UserInfoKey.feed] as? Feed else {
+ @objc func handleFeedIconImageDidChange(_ notification: Notification) {
+ guard showIcons, let feed = notification.userInfo?[UserInfoKey.feed] as? Feed else {
return
}
let indexesToReload = tableView.indexesOfAvailableRowsPassingTest { (row) -> Bool in
@@ -693,8 +778,8 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
}
}
- @objc func avatarDidBecomeAvailable(_ note: Notification) {
- guard showIcons, let avatarURL = note.userInfo?[UserInfoKey.url] as? String else {
+ @objc func handleAuthorAvatarImageDidChange(_ notification: Notification) {
+ guard showIcons, let avatarURL = notification.userInfo?[UserInfoKey.url] as? String else {
return
}
@@ -714,18 +799,91 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
}
}
- @objc func faviconDidBecomeAvailable(_ note: Notification) {
- guard showIcons, let faviconURL = note.userInfo?[FaviconDownloader.UserInfoKey.faviconURL] as? String else {
+ @objc func handleGrayscaleIconsDidChange(_ notification: Notification) {
+ guard showIcons else {
return
}
- let indexesToReload = tableView.indexesOfAvailableRowsPassingTest { (row) -> Bool in
- guard let article = articles.articleAtRow(row), let feed = article.feed else {
- return false
- }
- return FaviconDownloader.shared.cachedFaviconURL(for: feed) == faviconURL
+ reloadVisibleCells()
+ }
+
+ @objc func handleThumbnailDidBecomeAvailable(_ notification: Notification) {
+ guard let thumbnailMode, let url = notification.userInfo?[ThumbnailDownloader.urlKey] as? String else {
+ return
}
- if let indexesToReload = indexesToReload {
- reloadCells(for: indexesToReload)
+ // The row already has room for the thumbnail, so only the image changes.
+ tableView.enumerateAvailableRowViews { rowView, row in
+ guard let article = articles.articleAtRow(row), ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) == url, let cell = cellForRowView(rowView) as? TimelineTableCellView, let thumbnail = ThumbnailDownloader.shared.thumbnail(url: url, mode: thumbnailMode, articleTitle: article.title) else {
+ return
+ }
+ cell.thumbnail = thumbnail
+ }
+ }
+
+ @objc func handleArticleThumbnailDownloadDidFail(_ notification: Notification) {
+ guard thumbnailMode != nil, let articleIDs = notification.userInfo?[ArticleThumbnailFinder.articleIDsKey] as? Set else {
+ return
+ }
+ // Articles that used the failed URL now get their next source, or none.
+ thumbnailURLsDidChange(for: articleIDs)
+ }
+
+ @objc func handleNetworkStatusDidChange(_ notification: Notification) {
+ guard thumbnailMode != nil else {
+ return
+ }
+ // After ArticleThumbnailFinder forgets its choices, which it does on this notification too.
+ Task { @MainActor in
+ remeasureRowsWhoseThumbnailChanged()
+ // Thumbnails that couldn’t download while offline or in Low Data Mode try again.
+ if ThumbnailDownloader.shared.networkAllowsDownloads {
+ reloadVisibleCells()
+ }
+ }
+ }
+
+ @objc func handleTimelineShowSeparatorsDidChange(_ notification: Notification) {
+ updateGridStyle()
+ }
+
+ @objc func handleTimelineThumbnailsDisplayDidChange(_ notification: Notification) {
+ thumbnailsDisplay = AppDefaults.timelineThumbnailsDisplay
+ }
+
+ @objc func handleTimelineFeedIconsDisplayDidChange(_ notification: Notification) {
+ updateShowIcons()
+ if showIcons {
+ IconImageCache.shared.prefetchImagesForArticles(articles)
+ }
+ performBlockAndRestoreSelection {
+ tableView.reloadData()
+ }
+ }
+
+ @objc func handleTimelineTextSizeDidChange(_ notification: Notification) {
+ textSize = AppDefaults.timelineTextSize
+ }
+
+ @objc func handleTimelineNumberOfLinesDidChange(_ notification: Notification) {
+ numberOfLines = AppDefaults.timelineNumberOfLines
+ }
+
+ @objc func handleTimelineShowFullTitlesDidChange(_ notification: Notification) {
+ showFullTitles = AppDefaults.timelineShowFullTitles
+ }
+
+ @objc func handleTimelineFeedNameAndDateAboveTitleDidChange(_ notification: Notification) {
+ feedNameAndDateAboveTitle = AppDefaults.timelineFeedNameAndDateAboveTitle
+ }
+
+ @objc func handleTimelineFadeReadArticlesDidChange(_ notification: Notification) {
+ fadesReadArticles = AppDefaults.timelineFadeReadArticles
+ }
+
+ @objc func handleTimelineIconSizeDidChange(_ notification: Notification) {
+ updateCellAppearances()
+ rowHeights.removeAll()
+ performBlockAndRestoreSelection {
+ tableView.reloadData()
}
}
@@ -774,13 +932,18 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
}
}
- @MainActor func userDefaultsDidChange() {
- fontSize = AppDefaults.shared.timelineFontSize
+ /// Separators between rows, never in column layout. `TimelineTableRowView` draws them.
+ private func updateGridStyle() {
+ let showsSeparators = layout == .standard && AppDefaults.timelineShowSeparators
+ let gridStyleMask: NSTableView.GridLineStyle = showsSeparators ? .solidHorizontalGridLineMask : []
+ if tableView.gridStyleMask != gridStyleMask {
+ tableView.gridStyleMask = gridStyleMask
+ }
}
- /// The one place the row height is set — it depends on the layout and the font size.
+ /// The one place the row height is set. In standard layout, it’s the estimate for rows not yet measured.
func updateTableViewRowHeight() {
- tableView.rowHeight = layout == .column ? columnRowHeight() : currentRowHeight
+ tableView.rowHeight = layout == .column ? columnRowHeight() : estimatedRowHeight
}
// MARK: - Reloading Data
@@ -833,22 +996,205 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
// MARK: - Cell Configuring
- private func calculateRowHeight() -> CGFloat {
+ /// The full number of lines, with no icon or thumbnail.
+ private func calculateEstimatedRowHeight() -> CGFloat {
let longTitle = "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
let prototypeID = "prototype"
let status = ArticleStatus(articleID: prototypeID, read: false, starred: false, dateArrived: Date())
- let prototypeArticle = Article(accountID: prototypeID, articleID: prototypeID, feedID: prototypeID, uniqueID: prototypeID, title: longTitle, contentHTML: nil, contentText: nil, markdown: nil, url: nil, externalURL: nil, summary: nil, imageURL: nil, datePublished: nil, dateModified: nil, authors: nil, status: status)
+ let prototypeArticle = Article(accountID: prototypeID, articleID: prototypeID, feedID: prototypeID, uniqueID: prototypeID, title: longTitle, contentHTML: nil, contentText: nil, markdown: nil, url: nil, externalURL: nil, summary: nil, imageURL: nil, thumbnailURL: nil, datePublished: nil, dateModified: nil, authors: nil, attachments: nil, status: status)
- let prototypeCellData = TimelineCellData(article: prototypeArticle, showFeedName: .feed, feedName: "Prototype Feed Name", byline: nil, iconImage: nil, showIcon: false)
- let height = TimelineCellLayout.height(for: 100, cellData: prototypeCellData, appearance: cellAppearance)
- return height
+ let prototypeCellData = TimelineCellData(article: prototypeArticle, showFeedName: .feed, feedName: "Prototype Feed Name", byline: nil, iconImage: nil, showIcon: false, thumbnail: nil, showThumbnail: false)
+ return TimelineCellLayout.height(for: Self.prototypeRowWidth, cellData: prototypeCellData, appearance: cellAppearance)
}
- private func updateRowHeights() {
- currentRowHeight = calculateRowHeight()
+ private func updateEstimatedRowHeight() {
+ estimatedRowHeight = calculateEstimatedRowHeight()
updateTableViewRowHeight()
}
+ // MARK: - Row Heights
+
+ /// Nil when the row hasn’t been measured, or its article changed since.
+ private func measuredRowHeight(for article: Article) -> CGFloat? {
+ guard let rowHeight = rowHeights[ArticleIdentityKey(article)], rowHeight.article === article else {
+ return nil
+ }
+ return rowHeight.height
+ }
+
+ private func measureRowHeight(for article: Article) {
+ let showThumbnail = articleShowsThumbnail(article)
+ let cellData = TimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.feed?.nameForDisplay, byline: article.byline(), iconImage: nil, showIcon: showIcons, thumbnail: nil, showThumbnail: showThumbnail)
+ let appearance: TimelineCellAppearance = showIcons ? cellAppearanceWithIcon : cellAppearance
+ let height = TimelineCellLayout.height(for: rowHeightWidth, cellData: cellData, appearance: appearance)
+ rowHeights[ArticleIdentityKey(article)] = TimelineRowHeight(article: article, showsThumbnail: showThumbnail, height: height)
+ }
+
+ private func articleShowsThumbnail(_ article: Article) -> Bool {
+ guard let thumbnailMode else {
+ return false
+ }
+ return ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) != nil
+ }
+
+ /// Measures right away when there are few rows, so they don’t show the estimate first.
+ private func remeasureRowHeights(_ rows: IndexSet) {
+ guard layout == .standard, !rows.isEmpty else {
+ return
+ }
+ let measuresNow = rows.count <= Self.rowHeightBatchSize && rowHeightWidth > 0.0
+ for row in rows {
+ guard let article = articles.articleAtRow(row) else {
+ continue
+ }
+ rowHeights[ArticleIdentityKey(article)] = nil
+ if measuresNow {
+ measureRowHeight(for: article)
+ }
+ }
+ noteHeightOfRowsKeepingScrollPosition(rows)
+ }
+
+ /// `oldArticles` are the same articles in the same order. A changed article is a new instance.
+ private func rowsWithChangedArticles(comparedWith oldArticles: ArticleArray) -> IndexSet {
+ var rows = IndexSet()
+ for (row, (oldArticle, article)) in zip(oldArticles, articles).enumerated() where oldArticle !== article {
+ rows.insert(row)
+ }
+ return rows
+ }
+
+ /// For thumbnail choices that change with no failure notification, such as after a network change.
+ private func remeasureRowsWhoseThumbnailChanged() {
+ var rows = IndexSet()
+ for (row, article) in articles.enumerated() {
+ if let rowHeight = rowHeights[ArticleIdentityKey(article)], rowHeight.showsThumbnail != articleShowsThumbnail(article) {
+ rows.insert(row)
+ }
+ }
+ remeasureRowHeights(rows)
+ }
+
+ private func removeRowHeightsForMissingArticles() {
+ let articleKeys = Set(articles.map { ArticleIdentityKey($0) })
+ rowHeights = rowHeights.filter { articleKeys.contains($0.key) }
+ }
+
+ /// A width change makes every height stale. Rows near the visible ones are measured during layout, the rest in passes.
+ private func updateRowHeightWidth() {
+ let width = standardCellWidth()
+ guard width > 0.0, width != rowHeightWidth else {
+ return
+ }
+ rowHeightWidth = width
+ rowHeights.removeAll()
+ scheduleRowHeightMeasuring(from: 0)
+ }
+
+ /// A shown cell’s width when there is one. Otherwise the width the table gives cells.
+ private func standardCellWidth() -> CGFloat {
+ let visibleRows = tableView.rows(in: tableView.visibleRect)
+ if visibleRows.length > 0, let cell = tableView.view(atColumn: 0, row: visibleRows.location, makeIfNecessary: false) {
+ return cell.frame.width
+ }
+ if tableView.numberOfRows > 0 {
+ return tableView.frameOfCell(atColumn: 0, row: 0).width
+ }
+ guard let column = tableView.tableColumns.first else {
+ return 0.0
+ }
+ return column.width - tableView.intercellSpacing.width
+ }
+
+ /// The visible rows plus a screenful above and below, so scrolling a little doesn’t show estimates.
+ private func measureRowHeightsNearVisibleRows() {
+ guard rowHeightWidth > 0.0 else {
+ return
+ }
+ let visibleRect = tableView.visibleRect
+ let nearbyRows = tableView.rows(in: visibleRect.insetBy(dx: 0.0, dy: -visibleRect.height))
+ guard nearbyRows.length > 0 else {
+ return
+ }
+ var measuredRows = IndexSet()
+ for row in nearbyRows.location.. 0.0, !tableView.inLiveResize else {
+ return
+ }
+ rowHeightMeasuringStartRow = nil
+
+ var measuredRows = IndexSet()
+ var row = startRow
+ while row < articles.count && measuredRows.count < Self.rowHeightBatchSize {
+ let article = articles[row]
+ if measuredRowHeight(for: article) == nil {
+ measureRowHeight(for: article)
+ measuredRows.insert(row)
+ }
+ row += 1
+ }
+
+ if !measuredRows.isEmpty {
+ noteHeightOfRowsKeepingScrollPosition(measuredRows)
+ }
+ if row < articles.count {
+ scheduleRowHeightMeasuring(from: row)
+ }
+ }
+
+ /// Keeps the top visible row in place when rows above it change height.
+ private func noteHeightOfRowsKeepingScrollPosition(_ rowIndexes: IndexSet) {
+ guard let scrollView = tableView.enclosingScrollView else {
+ noteHeightOfRowsWithoutAnimation(rowIndexes)
+ return
+ }
+ let clipView = scrollView.contentView
+ let topY = clipView.bounds.minY
+ let topRow = tableView.row(at: NSPoint(x: 0, y: max(topY, 0)))
+ guard topRow > 0, let firstChangedRow = rowIndexes.first, firstChangedRow < topRow else {
+ noteHeightOfRowsWithoutAnimation(rowIndexes)
+ return
+ }
+
+ let offsetIntoTopRow = topY - tableView.rect(ofRow: topRow).minY
+ noteHeightOfRowsWithoutAnimation(rowIndexes)
+ clipView.scroll(to: NSPoint(x: clipView.bounds.minX, y: tableView.rect(ofRow: topRow).minY + offsetIntoTopRow))
+ scrollView.reflectScrolledClipView(clipView)
+ }
+
+ private func noteHeightOfRowsWithoutAnimation(_ rowIndexes: IndexSet) {
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0
+ tableView.noteHeightOfRows(withIndexesChanged: rowIndexes)
+ }
+ }
+
@objc func fetchAndMergeArticles() {
guard let representedObjects = representedObjects else {
return
@@ -929,10 +1275,36 @@ extension TimelineViewController: NSTableViewDataSource {
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
// Keeping -[NSTableViewDelegate tableView:heightOfRow:] implemented fixes
// an issue that the bottom inset of NSTableView disappears on macOS Monterey.
+ guard layout == .standard, let article = articles.articleAtRow(row) else {
+ return tableView.rowHeight
+ }
+ if let height = measuredRowHeight(for: article) {
+ return height
+ }
+ scheduleRowHeightMeasuring(from: row)
return tableView.rowHeight
}
}
+// MARK: - TimelineTableViewRowHeightDelegate
+
+extension TimelineViewController: TimelineTableViewRowHeightDelegate {
+
+ func timelineTableViewDidLayout(_ tableView: TimelineTableView) {
+ guard layout == .standard else {
+ return
+ }
+ updateRowHeightWidth()
+ measureRowHeightsNearVisibleRows()
+ }
+
+ func timelineTableViewDidEndLiveResize(_ tableView: TimelineTableView) {
+ if let rowHeightMeasuringStartRow {
+ scheduleRowHeightMeasuring(from: rowHeightMeasuringStartRow)
+ }
+ }
+}
+
// MARK: - NSTableViewDelegate
extension TimelineViewController: NSTableViewDelegate {
@@ -943,25 +1315,37 @@ extension TimelineViewController: NSTableViewDelegate {
// The standard row view suits column layout. TimelineTableRowView only knows the standard cell.
return nil
}
- if let rowView: TimelineTableRowView = tableView.makeView(withIdentifier: TimelineViewController.rowViewIdentifier, owner: nil) as? TimelineTableRowView {
- return rowView
+ let rowView: TimelineTableRowView
+ if let reusedRowView = tableView.makeView(withIdentifier: TimelineViewController.rowViewIdentifier, owner: nil) as? TimelineTableRowView {
+ rowView = reusedRowView
+ } else {
+ rowView = TimelineTableRowView()
+ rowView.identifier = TimelineViewController.rowViewIdentifier
}
- let rowView = TimelineTableRowView()
- rowView.identifier = TimelineViewController.rowViewIdentifier
+ // Rows change only by reloading, which asks for every row view again, so a former last row doesn’t keep this.
+ rowView.isLastRow = row == tableView.numberOfRows - 1
return rowView
}
private static let timelineCellIdentifier = NSUserInterfaceItemIdentifier(rawValue: "timelineCell")
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
- if layout == .column {
- return columnCellView(for: tableColumn, row: row)
+ let cellView = layout == .column ? columnCellView(for: tableColumn, row: row) : standardCellView(for: row)
+ if let cellView {
+ applyReadFading(to: cellView, row: row)
}
+ return cellView
+ }
+ private func standardCellView(for row: Int) -> NSView {
func configure(_ cell: TimelineTableCellView) {
cell.cellAppearance = showIcons ? cellAppearanceWithIcon : cellAppearance
if let article = articles.articleAtRow(row) {
configureTimelineCell(cell, article: article)
+ if measuredRowHeight(for: article) == nil {
+ // Measured after layout, before it draws.
+ tableView.needsLayout = true
+ }
} else {
makeTimelineCellEmpty(cell)
}
@@ -979,6 +1363,8 @@ extension TimelineViewController: NSTableViewDelegate {
}
func tableViewSelectionDidChange(_ notification: Notification) {
+ applyReadFadingToAvailableRows()
+
if selectedArticles.isEmpty {
selectionDidChange(nil)
return
@@ -998,7 +1384,7 @@ extension TimelineViewController: NSTableViewDelegate {
// Compare by identity, not content — re-pushing an updated article that the user is reading
// would reset the article view scroll position.
//
- let selectedArticleKeys = selectedArticles?.map { ArticleIdentityKey(accountID: $0.accountID, articleID: $0.articleID) }
+ let selectedArticleKeys = selectedArticles?.map { ArticleIdentityKey($0) }
guard selectedArticleKeys != previouslySelectedArticleKeys else {
return
}
@@ -1009,19 +1395,37 @@ extension TimelineViewController: NSTableViewDelegate {
private func configureTimelineCell(_ cell: TimelineTableCellView, article: Article) {
cell.objectValue = article
- let iconImage = article.iconImage()
- cell.cellData = TimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.feed?.nameForDisplay, byline: article.byline(), iconImage: iconImage, showIcon: showIcons)
- }
-
- private func iconFor(_ article: Article) -> IconImage? {
- if !showIcons {
- return nil
+ let iconImage = showIcons ? article.iconImage() : nil
+ var thumbnail: NSImage?
+ var showThumbnail = false
+ if let thumbnailMode, let thumbnailURL = ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) {
+ showThumbnail = true
+ thumbnail = ThumbnailDownloader.shared.thumbnail(url: thumbnailURL, mode: thumbnailMode, articleTitle: article.title)
}
- return IconImageCache.shared.imageForArticle(article)
+ cell.cellData = TimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.feed?.nameForDisplay, byline: article.byline(), iconImage: iconImage, showIcon: showIcons, thumbnail: thumbnail, showThumbnail: showThumbnail)
}
- private func avatarForAuthor(_ author: Author) -> IconImage? {
- return AuthorAvatarDownloader.shared.image(for: author)
+ /// Fades the cell views, not the row view, so the selection highlight and separators stay full strength.
+ /// The selected row never fades, since selecting an article marks it read.
+ private func applyReadFading(to cellView: NSView, row: Int) {
+ var alphaValue: CGFloat = 1.0
+ if fadesReadArticles, let article = articles.articleAtRow(row), article.status.read, !tableView.isRowSelected(row) {
+ alphaValue = Self.readArticleAlphaValue
+ }
+ if cellView.alphaValue != alphaValue {
+ cellView.alphaValue = alphaValue
+ }
+ }
+
+ /// Selection changes don’t reload cells.
+ private func applyReadFadingToAvailableRows() {
+ tableView.enumerateAvailableRowViews { rowView, row in
+ for column in 0.. 0, tableView.frame.width != visibleWidth else {
+ return
+ }
+ tableView.setFrameSize(NSSize(width: visibleWidth, height: tableView.frame.height))
+ tableView.sizeLastColumnToFit()
+ }
+
+ /// Returns true if it scrolled. Callers should skip further scrolling then,
+ /// since the animation hasn’t updated the visible rect yet.
+ ///
+ @discardableResult func scrollToRowIfNotFullyVisible(_ row: Int) -> Bool {
+ guard (0..) {
+ guard !articleIDs.isEmpty else {
+ return
+ }
+ if thumbnailMode != nil {
+ remeasureRowHeights(indexesForArticleIDs(articleIDs))
+ }
+ reloadVisibleCells(for: articleIDs)
+ }
+
+ func thumbnailsDisplayDidChange() {
+ updateCellAppearances()
+ rowHeights.removeAll()
+ guard layout == .standard else {
+ return
+ }
+ performBlockAndRestoreSelection {
+ tableView.reloadData()
+ }
+ if tableView.selectedRow != -1 {
+ tableView.scrollRowToVisible(tableView.selectedRow)
+ }
+ }
+
// MARK: - Appearance Change
- private func fontSizeDidChange() {
- cellAppearance = TimelineCellAppearance(showIcon: false, fontSize: fontSize)
- cellAppearanceWithIcon = TimelineCellAppearance(showIcon: true, fontSize: fontSize)
- updateRowHeights()
+ private func updateCellAppearances() {
+ let iconSize = AppDefaults.timelineIconSize
+ cellAppearance = TimelineCellAppearance(showIcon: false, textSize: textSize, iconSize: iconSize, numberOfLines: numberOfLines, showsFullTitles: showFullTitles, feedNameAndDateAboveTitle: feedNameAndDateAboveTitle, showsLargeThumbnails: thumbnailsDisplay == .large)
+ cellAppearanceWithIcon = TimelineCellAppearance(showIcon: true, textSize: textSize, iconSize: iconSize, numberOfLines: numberOfLines, showsFullTitles: showFullTitles, feedNameAndDateAboveTitle: feedNameAndDateAboveTitle, showsLargeThumbnails: thumbnailsDisplay == .large)
+ }
+
+ private func cellAppearanceSettingDidChange() {
+ updateCellAppearances()
+ updateEstimatedRowHeight()
+ rowHeights.removeAll()
performBlockAndRestoreSelection {
tableView.reloadData()
}
@@ -1316,7 +1791,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/Mac/Preferences/Accounts/AddAccountHelpView.swift b/Mac/Preferences/Accounts/AddAccountHelpView.swift
index 8ef5517cf..d729eeccf 100644
--- a/Mac/Preferences/Accounts/AddAccountHelpView.swift
+++ b/Mac/Preferences/Accounts/AddAccountHelpView.swift
@@ -25,7 +25,7 @@ struct AddAccountHelpView: View {
ForEach(accountTypes, id: \.self) { accountType in
if accountType == .cloudKit && hasiCloudAccount {
EmptyView()
- } else if !(AppDefaults.shared.isDeveloperBuild && accountType.isDeveloperRestricted) {
+ } else if !(AppDefaults.isDeveloperBuild && accountType.isDeveloperRestricted) {
Button(action: {
delegate?.presentSheetForAccount(accountType)
}, label: {
diff --git a/Mac/Preferences/Accounts/AddAccountsView.swift b/Mac/Preferences/Accounts/AddAccountsView.swift
index 4dd1fff6e..3831fa107 100644
--- a/Mac/Preferences/Accounts/AddAccountsView.swift
+++ b/Mac/Preferences/Accounts/AddAccountsView.swift
@@ -54,7 +54,7 @@ enum AddAccountSections: Int, CaseIterable {
case .icloud:
return [.cloudKit]
case .web:
- if AppDefaults.shared.isDeveloperBuild {
+ if AppDefaults.isDeveloperBuild {
return [.bazQux, .feedbin, .feedly, .inoreader, .newsBlur, .theOldReader].filter({ $0.isDeveloperRestricted == false })
} else {
return [.bazQux, .feedbin, .feedly, .inoreader, .newsBlur, .theOldReader]
@@ -89,7 +89,7 @@ struct AddAccountsView: View {
localAccount
- if !AppDefaults.shared.isDeveloperBuild {
+ if !AppDefaults.isDeveloperBuild {
icloudAccount
}
diff --git a/Mac/Preferences/Appearance/AppearancePreferencesViewController.swift b/Mac/Preferences/Appearance/AppearancePreferencesViewController.swift
new file mode 100644
index 000000000..3e4f4b485
--- /dev/null
+++ b/Mac/Preferences/Appearance/AppearancePreferencesViewController.swift
@@ -0,0 +1,221 @@
+//
+// AppearancePreferencesViewController.swift
+// NetNewsWire
+//
+// Created by Brent Simmons on 11/6/26.
+//
+
+import AppKit
+import RSCore
+
+final class AppearancePreferencesViewController: NSViewController {
+
+ @IBOutlet var appearancePopup: NSPopUpButton?
+ @IBOutlet var grayscaleIconsButton: NSButton?
+
+ @IBOutlet var sidebarShowFeedIconsButton: NSButton?
+ @IBOutlet var sidebarTextSizePopup: NSPopUpButton?
+ @IBOutlet var sidebarShowTodayButton: NSButton?
+ @IBOutlet var sidebarShowAllUnreadButton: NSButton?
+ @IBOutlet var sidebarShowStarredButton: NSButton?
+
+ @IBOutlet var articleTextSizeLabel: NSTextField?
+ @IBOutlet var articleTextSizePopup: NSPopUpButton?
+ @IBOutlet var articleThemePopup: NSPopUpButton?
+
+ convenience init() {
+ self.init(nibName: "AppearancePreferencesView", bundle: nil)
+ }
+
+ override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
+ super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
+ commonInit()
+ }
+
+ required init?(coder: NSCoder) {
+ super.init(coder: coder)
+ commonInit()
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+ fixArticleTextSizeBaselineIfNeeded()
+ view.sizeToFittingSize()
+ }
+
+ override func viewWillAppear() {
+ super.viewWillAppear()
+ updateAppearancePopup()
+ updateGrayscaleIconsButton()
+ updateSidebarShowIconsButton()
+ updateSidebarTextSizePopup()
+ updateSmartFeedsButtons()
+ updateArticleThemePopup()
+ }
+
+ // MARK: - Notifications
+
+ @objc func handleApplicationWillBecomeActive(_ notification: Notification) {
+ updateArticleThemePopup()
+ }
+
+ @objc func handleArticleThemeNamesDidChange(_ notification: Notification) {
+ updateArticleThemePopup()
+ }
+
+ @objc func handleUserInterfaceColorPaletteDidUpdate(_ notification: Notification) {
+ updateAppearancePopup()
+ }
+
+ @objc func handleGrayscaleIconsDidChange(_ notification: Notification) {
+ updateGrayscaleIconsButton()
+ }
+
+ @objc func handleSidebarShowsIconsDidChange(_ notification: Notification) {
+ updateSidebarShowIconsButton()
+ }
+
+ @objc func handleSidebarTextSizeDidChange(_ notification: Notification) {
+ updateSidebarTextSizePopup()
+ }
+
+ @objc func handleSidebarSmartFeedsVisibilityDidChange(_ notification: Notification) {
+ updateSmartFeedsButtons()
+ }
+
+ // MARK: - Actions
+
+ @IBAction func appearancePopUpDidChange(_ sender: Any) {
+ guard let tag = appearancePopup?.selectedTag(), let colorPalette = UserInterfaceColorPalette(rawValue: tag) else {
+ return
+ }
+ AppDefaults.userInterfaceColorPalette = colorPalette
+ }
+
+ @IBAction func grayscaleIconsDidChange(_ sender: NSButton) {
+ AppDefaults.grayscaleIcons = sender.state == .on
+ }
+
+ @IBAction func sidebarShowIconsDidChange(_ sender: NSButton) {
+ AppDefaults.sidebarShowsIcons = sender.state == .on
+ }
+
+ @IBAction func sidebarTextSizePopUpDidChange(_ sender: Any) {
+ guard let tag = sidebarTextSizePopup?.selectedTag(), let textSize = SidebarTextSize(rawValue: tag) else {
+ return
+ }
+ AppDefaults.sidebarTextSize = textSize
+ }
+
+ @IBAction func sidebarShowTodayDidChange(_ sender: NSButton) {
+ AppDefaults.showTodayFeed = sender.state == .on
+ }
+
+ @IBAction func sidebarShowAllUnreadDidChange(_ sender: NSButton) {
+ AppDefaults.showUnreadFeed = sender.state == .on
+ }
+
+ @IBAction func sidebarShowStarredDidChange(_ sender: NSButton) {
+ AppDefaults.showStarredFeed = sender.state == .on
+ }
+
+ @IBAction func showThemesFolder(_ sender: Any) {
+ let url = URL(fileURLWithPath: ArticleThemesManager.shared.folderPath)
+ NSWorkspace.shared.open(url)
+ }
+
+ @IBAction func articleThemePopUpDidChange(_ sender: Any) {
+ guard let menuItem = articleThemePopup?.selectedItem else {
+ return
+ }
+ ArticleThemesManager.shared.currentThemeName = menuItem.title
+ updateArticleThemePopup()
+ }
+}
+
+// MARK: - Private
+
+private extension AppearancePreferencesViewController {
+
+ func commonInit() {
+ NotificationCenter.default.addObserver(self, selector: #selector(handleApplicationWillBecomeActive(_:)), name: NSApplication.willBecomeActiveNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThemeNamesDidChange(_:)), name: .ArticleThemeNamesDidChangeNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleUserInterfaceColorPaletteDidUpdate(_:)), name: .userInterfaceColorPaletteDidUpdate, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleGrayscaleIconsDidChange(_:)), name: .grayscaleIconsDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleSidebarShowsIconsDidChange(_:)), name: .sidebarShowsIconsDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleSidebarTextSizeDidChange(_:)), name: .sidebarTextSizeDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleSidebarSmartFeedsVisibilityDidChange(_:)), name: .sidebarSmartFeedsVisibilityDidChange, object: nil)
+ }
+
+ /// On macOS 15 the "Article Text Size:" label is vertically misaligned
+ /// with its popup. Replace the firstBaseline constraint with a
+ /// centerY constraint, which works.
+ func fixArticleTextSizeBaselineIfNeeded() {
+ if #available(macOS 26, *) {
+ return
+ }
+
+ guard let articleTextSizeLabel, let articleTextSizePopup, let superview = articleTextSizeLabel.superview else {
+ return
+ }
+
+ for constraint in superview.constraints {
+ let matchesBaseline =
+ constraint.firstAttribute == .firstBaseline &&
+ constraint.secondAttribute == .firstBaseline
+ let involvesPopup =
+ constraint.firstItem === articleTextSizePopup ||
+ constraint.secondItem === articleTextSizePopup
+ let involvesLabel =
+ constraint.firstItem === articleTextSizeLabel ||
+ constraint.secondItem === articleTextSizeLabel
+
+ if matchesBaseline && involvesPopup && involvesLabel {
+ superview.removeConstraint(constraint)
+ articleTextSizeLabel.centerYAnchor.constraint(equalTo: articleTextSizePopup.centerYAnchor).isActive = true
+ break
+ }
+ }
+ }
+
+ func updateAppearancePopup() {
+ appearancePopup?.selectItem(withTag: AppDefaults.userInterfaceColorPalette.rawValue)
+ }
+
+ func updateGrayscaleIconsButton() {
+ grayscaleIconsButton?.state = AppDefaults.grayscaleIcons ? .on : .off
+ }
+
+ func updateSidebarShowIconsButton() {
+ sidebarShowFeedIconsButton?.state = AppDefaults.sidebarShowsIcons ? .on : .off
+ }
+
+ func updateSidebarTextSizePopup() {
+ sidebarTextSizePopup?.selectItem(withTag: AppDefaults.sidebarTextSize.rawValue)
+ }
+
+ func updateSmartFeedsButtons() {
+ sidebarShowTodayButton?.state = AppDefaults.showTodayFeed ? .on : .off
+ sidebarShowAllUnreadButton?.state = AppDefaults.showUnreadFeed ? .on : .off
+ sidebarShowStarredButton?.state = AppDefaults.showStarredFeed ? .on : .off
+ }
+
+ func updateArticleThemePopup() {
+ guard let articleThemePopup, let menu = articleThemePopup.menu else {
+ return
+ }
+ menu.removeAllItems()
+
+ menu.addItem(NSMenuItem(title: ArticleTheme.defaultTheme.name, action: nil, keyEquivalent: ""))
+ menu.addItem(NSMenuItem.separator())
+
+ for themeName in ArticleThemesManager.shared.themeNames {
+ menu.addItem(NSMenuItem(title: themeName, action: nil, keyEquivalent: ""))
+ }
+
+ articleThemePopup.selectItem(withTitle: ArticleThemesManager.shared.currentThemeName)
+ if articleThemePopup.indexOfSelectedItem == -1 {
+ articleThemePopup.selectItem(withTitle: ArticleTheme.defaultTheme.name)
+ }
+ }
+}
diff --git a/Mac/Preferences/Appearance/Base.lproj/AppearancePreferencesView.xib b/Mac/Preferences/Appearance/Base.lproj/AppearancePreferencesView.xib
new file mode 100644
index 000000000..0c6e6ff78
--- /dev/null
+++ b/Mac/Preferences/Appearance/Base.lproj/AppearancePreferencesView.xib
@@ -0,0 +1,319 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Mac/Preferences/Appearance/mul.lproj/AppearancePreferencesView.xcstrings b/Mac/Preferences/Appearance/mul.lproj/AppearancePreferencesView.xcstrings
new file mode 100644
index 000000000..aa61c0277
--- /dev/null
+++ b/Mac/Preferences/Appearance/mul.lproj/AppearancePreferencesView.xcstrings
@@ -0,0 +1,390 @@
+{
+ "sourceLanguage" : "en",
+ "strings" : {
+ "4Pi-2Y-XmV.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Extra Extra Large\"; ObjectID = \"4Pi-2Y-XmV\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Extra Extra Large"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Extra extra grande"
+ }
+ }
+ }
+ },
+ "apL-cM-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Appearance:\"; ObjectID = \"apL-cM-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Appearance:"
+ }
+ }
+ }
+ },
+ "apM-cM-0m0.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"System\"; ObjectID = \"apM-cM-0m0\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "System"
+ }
+ }
+ }
+ },
+ "apM-cM-0m1.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Light\"; ObjectID = \"apM-cM-0m1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Light"
+ }
+ }
+ }
+ },
+ "apM-cM-0m2.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Dark\"; ObjectID = \"apM-cM-0m2\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Dark"
+ }
+ }
+ }
+ },
+ "ckZ-0Q-rNz.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Large\"; ObjectID = \"ckZ-0Q-rNz\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Large"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Grande"
+ }
+ }
+ }
+ },
+ "gyB-iC-0c1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"Grayscale icons\"; ObjectID = \"gyB-iC-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Grayscale icons"
+ }
+ }
+ }
+ },
+ "gyL-iC-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"This is for feed icons and author avatars. Article thumbnails remain in color.\"; ObjectID = \"gyL-iC-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "This is for feed icons and author avatars. Article thumbnails remain in color."
+ }
+ }
+ }
+ },
+ "jMV-2o-5Oh.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Medium\"; ObjectID = \"jMV-2o-5Oh\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Medium"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Mediano"
+ }
+ }
+ }
+ },
+ "MQe-Za-N8J.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Article Theme:\"; ObjectID = \"MQe-Za-N8J\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Article Theme:"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tema del artículo:"
+ }
+ }
+ }
+ },
+ "Pkl-EA-Goa.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Default\"; ObjectID = \"Pkl-EA-Goa\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Default"
+ }
+ }
+ }
+ },
+ "qMe-6g-Vme.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Extra Large\"; ObjectID = \"qMe-6g-Vme\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Extra Large"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Extra grande"
+ }
+ }
+ }
+ },
+ "roB-Mu-Ht7.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Small\"; ObjectID = \"roB-Mu-Ht7\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Small"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Pequeño"
+ }
+ }
+ }
+ },
+ "sbB-aU-0c1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"All Unread\"; ObjectID = \"sbB-aU-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "All Unread"
+ }
+ }
+ }
+ },
+ "sbB-fI-0c1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"Show\"; ObjectID = \"sbB-fI-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Show"
+ }
+ }
+ }
+ },
+ "sbB-sT-0c1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"Starred\"; ObjectID = \"sbB-sT-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Starred"
+ }
+ }
+ }
+ },
+ "sbB-tD-0c1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"Today\"; ObjectID = \"sbB-tD-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Today"
+ }
+ }
+ }
+ },
+ "sbL-fI-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Sidebar Icons:\"; ObjectID = \"sbL-fI-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Sidebar Icons:"
+ }
+ }
+ }
+ },
+ "sbL-sF-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Smart Feeds:\"; ObjectID = \"sbL-sF-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Smart Feeds:"
+ }
+ }
+ }
+ },
+ "sbL-tX-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Sidebar Text Size:\"; ObjectID = \"sbL-tX-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Sidebar Text Size:"
+ }
+ }
+ }
+ },
+ "sbM-tX-0m0.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"System\"; ObjectID = \"sbM-tX-0m0\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "System"
+ }
+ }
+ }
+ },
+ "sbM-tX-0m1.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Small\"; ObjectID = \"sbM-tX-0m1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Small"
+ }
+ }
+ }
+ },
+ "sbM-tX-0m2.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Medium\"; ObjectID = \"sbM-tX-0m2\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Medium"
+ }
+ }
+ }
+ },
+ "sbM-tX-0m3.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Large\"; ObjectID = \"sbM-tX-0m3\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Large"
+ }
+ }
+ }
+ },
+ "sbM-tX-0m4.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Extra Large\"; ObjectID = \"sbM-tX-0m4\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Extra Large"
+ }
+ }
+ }
+ },
+ "sbM-tX-0m5.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Extra Extra Large\"; ObjectID = \"sbM-tX-0m5\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Extra Extra Large"
+ }
+ }
+ }
+ },
+ "xQu-QV-91i.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Article Text Size:\"; ObjectID = \"xQu-QV-91i\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Article Text Size:"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tamaño del texto:"
+ }
+ }
+ }
+ },
+ "ySX-5i-SP1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"Open Themes Folder\"; ObjectID = \"ySX-5i-SP1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Open Themes Folder"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Abrir carpeta de temas"
+ }
+ }
+ }
+ }
+ },
+ "version" : "1.2"
+}
\ No newline at end of file
diff --git a/Mac/Preferences/General/Base.lproj/GeneralPreferencesView.xib b/Mac/Preferences/General/Base.lproj/GeneralPreferencesView.xib
index 1335e4d9b..562e94292 100644
--- a/Mac/Preferences/General/Base.lproj/GeneralPreferencesView.xib
+++ b/Mac/Preferences/General/Base.lproj/GeneralPreferencesView.xib
@@ -7,9 +7,6 @@
-
-
-
@@ -20,14 +17,14 @@
-
+
-
+
-
+
@@ -35,7 +32,7 @@
-
+
@@ -45,7 +42,7 @@
-
+
@@ -55,7 +52,7 @@
-
+
@@ -65,81 +62,8 @@
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -149,7 +73,7 @@
-
+
@@ -169,7 +93,7 @@
-
+
@@ -177,7 +101,7 @@
-
+
@@ -188,7 +112,7 @@
-
+
@@ -203,7 +127,7 @@
-
+
@@ -223,7 +147,7 @@
-
+
@@ -239,7 +163,7 @@
-
+
@@ -253,7 +177,7 @@
-
+
@@ -263,7 +187,7 @@
-
+
@@ -274,7 +198,7 @@
-
+
@@ -309,51 +233,38 @@
-
-
-
+
-
-
+
-
+
-
-
+
-
-
-
+
-
-
-
-
+
+
-
+
-
-
-
-
-
-
+
@@ -361,25 +272,23 @@
-
+
-
+
-
+
-
+
-
-
-
-
+
+
diff --git a/Mac/Preferences/General/GeneralPrefencesViewController.swift b/Mac/Preferences/General/GeneralPrefencesViewController.swift
index 9da98e2cf..566110d6a 100644
--- a/Mac/Preferences/General/GeneralPrefencesViewController.swift
+++ b/Mac/Preferences/General/GeneralPrefencesViewController.swift
@@ -13,9 +13,6 @@ import UserNotifications
import UniformTypeIdentifiers
final class GeneralPreferencesViewController: NSViewController {
- @IBOutlet var articleTextSizeLabel: NSTextField!
- @IBOutlet var articleTextSizePopup: NSPopUpButton!
- @IBOutlet var articleThemePopup: NSPopUpButton!
@IBOutlet var defaultBrowserPopup: NSPopUpButton!
@IBOutlet var showUnreadCountsButton: NSButton?
@IBOutlet var showUnreadCountDotButton: NSButton?
@@ -37,7 +34,6 @@ final class GeneralPreferencesViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
- fixArticleTextSizeBaselineIfNeeded()
view.sizeToFittingSize()
}
@@ -53,34 +49,17 @@ final class GeneralPreferencesViewController: NSViewController {
updateUI()
}
- @objc func articleThemeNamesDidChangeNotification(_ note: Notification) {
- updateArticleThemePopup()
- }
-
@objc func handleUnreadCountDisplaySettingDidChange(_ notification: Notification) {
updateUnreadCountDisplayButtons()
}
// MARK: - Actions
- @IBAction func showThemesFolder(_ sender: Any) {
- let url = URL(fileURLWithPath: ArticleThemesManager.shared.folderPath)
- NSWorkspace.shared.open(url)
- }
-
- @IBAction func articleThemePopUpDidChange(_ sender: Any) {
- guard let menuItem = articleThemePopup.selectedItem else {
- return
- }
- ArticleThemesManager.shared.currentThemeName = menuItem.title
- updateArticleThemePopup()
- }
-
@IBAction func unreadCountDisplaySettingDidChange(_ sender: NSButton) {
guard let unreadCountDisplay = UnreadCountDisplay(rawValue: sender.tag) else {
return
}
- AppDefaults.shared.unreadCountDisplay = unreadCountDisplay
+ AppDefaults.unreadCountDisplay = unreadCountDisplay
}
@IBAction func browserPopUpDidChangeValue(_ sender: Any?) {
@@ -89,7 +68,7 @@ final class GeneralPreferencesViewController: NSViewController {
}
let bundleID = menuItem.representedObject as? String
- AppDefaults.shared.defaultBrowserID = bundleID
+ AppDefaults.defaultBrowserID = bundleID
updateBrowserPopup()
}
@@ -99,73 +78,23 @@ final class GeneralPreferencesViewController: NSViewController {
private extension GeneralPreferencesViewController {
- /// On macOS 15 the "Article Text Size:" label is vertically misaligned
- /// with its popup. Replace the firstBaseline constraint with a
- /// centerY constraint, which works.
- func fixArticleTextSizeBaselineIfNeeded() {
- if #available(macOS 26, *) {
- return
- }
-
- guard let superview = articleTextSizeLabel.superview else {
- return
- }
-
- for constraint in superview.constraints {
- let matchesBaseline =
- constraint.firstAttribute == .firstBaseline &&
- constraint.secondAttribute == .firstBaseline
- let involvesPopup =
- constraint.firstItem === articleTextSizePopup ||
- constraint.secondItem === articleTextSizePopup
- let involvesLabel =
- constraint.firstItem === articleTextSizeLabel ||
- constraint.secondItem === articleTextSizeLabel
-
- if matchesBaseline && involvesPopup && involvesLabel {
- superview.removeConstraint(constraint)
- articleTextSizeLabel.centerYAnchor.constraint(equalTo: articleTextSizePopup.centerYAnchor).isActive = true
- break
- }
- }
- }
-
func commonInit() {
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillBecomeActive(_:)), name: NSApplication.willBecomeActiveNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(articleThemeNamesDidChangeNotification(_:)), name: .ArticleThemeNamesDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleUnreadCountDisplaySettingDidChange(_:)), name: .unreadCountDisplaySettingDidChange, object: nil)
}
func updateUI() {
- updateArticleThemePopup()
updateBrowserPopup()
updateUnreadCountDisplayButtons()
}
func updateUnreadCountDisplayButtons() {
- let selectedTag = AppDefaults.shared.unreadCountDisplay.rawValue
+ let selectedTag = AppDefaults.unreadCountDisplay.rawValue
for case let button? in [showUnreadCountsButton, showUnreadCountDotButton, hideUnreadCountsButton] {
button.state = button.tag == selectedTag ? .on : .off
}
}
- func updateArticleThemePopup() {
- let menu = articleThemePopup.menu!
- menu.removeAllItems()
-
- menu.addItem(NSMenuItem(title: ArticleTheme.defaultTheme.name, action: nil, keyEquivalent: ""))
- menu.addItem(NSMenuItem.separator())
-
- for themeName in ArticleThemesManager.shared.themeNames {
- menu.addItem(NSMenuItem(title: themeName, action: nil, keyEquivalent: ""))
- }
-
- articleThemePopup.selectItem(withTitle: ArticleThemesManager.shared.currentThemeName)
- if articleThemePopup.indexOfSelectedItem == -1 {
- articleThemePopup.selectItem(withTitle: ArticleTheme.defaultTheme.name)
- }
- }
-
func updateBrowserPopup() {
let menu = defaultBrowserPopup.menu!
let allBrowsers = MacWebBrowser.sortedBrowsers()
@@ -221,7 +150,7 @@ private extension GeneralPreferencesViewController {
menu.addItem(item)
}
- defaultBrowserPopup.selectItem(at: defaultBrowserPopup.indexOfItem(withRepresentedObject: AppDefaults.shared.defaultBrowserID))
+ defaultBrowserPopup.selectItem(at: defaultBrowserPopup.indexOfItem(withRepresentedObject: AppDefaults.defaultBrowserID))
}
func updateNotificationSettings() {
@@ -236,10 +165,10 @@ private extension GeneralPreferencesViewController {
@objc var openFeedsInDefaultNewsReader: Bool {
get {
- return AppDefaults.shared.subscribeToFeedsInDefaultBrowser
+ return AppDefaults.subscribeToFeedsInDefaultBrowser
}
set {
- AppDefaults.shared.subscribeToFeedsInDefaultBrowser = newValue
+ AppDefaults.subscribeToFeedsInDefaultBrowser = newValue
}
}
}
diff --git a/Mac/Preferences/General/mul.lproj/GeneralPreferencesView.xcstrings b/Mac/Preferences/General/mul.lproj/GeneralPreferencesView.xcstrings
index ad21178db..9eb0bbed3 100644
--- a/Mac/Preferences/General/mul.lproj/GeneralPreferencesView.xcstrings
+++ b/Mac/Preferences/General/mul.lproj/GeneralPreferencesView.xcstrings
@@ -1,24 +1,6 @@
{
"sourceLanguage" : "en",
"strings" : {
- "4Pi-2Y-XmV.title" : {
- "comment" : "Class = \"NSMenuItem\"; title = \"Extra Extra Large\"; ObjectID = \"4Pi-2Y-XmV\";",
- "extractionState" : "extracted_with_value",
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "new",
- "value" : "Extra Extra Large"
- }
- },
- "es" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Extra extra grande"
- }
- }
- }
- },
"7e2-TV-hth.title" : {
"comment" : "Class = \"NSMenuItem\"; title = \"Every 4 hours\"; ObjectID = \"7e2-TV-hth\";",
"extractionState" : "extracted_with_value",
@@ -91,24 +73,6 @@
}
}
},
- "ckZ-0Q-rNz.title" : {
- "comment" : "Class = \"NSMenuItem\"; title = \"Large\"; ObjectID = \"ckZ-0Q-rNz\";",
- "extractionState" : "extracted_with_value",
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "new",
- "value" : "Large"
- }
- },
- "es" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Grande"
- }
- }
- }
- },
"doa-Wq-4Uq.title" : {
"comment" : "Class = \"NSMenuItem\"; title = \"Manually only\"; ObjectID = \"doa-Wq-4Uq\";",
"extractionState" : "extracted_with_value",
@@ -217,42 +181,6 @@
}
}
},
- "jMV-2o-5Oh.title" : {
- "comment" : "Class = \"NSMenuItem\"; title = \"Medium\"; ObjectID = \"jMV-2o-5Oh\";",
- "extractionState" : "extracted_with_value",
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "new",
- "value" : "Medium"
- }
- },
- "es" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Mediano"
- }
- }
- }
- },
- "MQe-Za-N8J.title" : {
- "comment" : "Class = \"NSTextFieldCell\"; title = \"Article Theme:\"; ObjectID = \"MQe-Za-N8J\";",
- "extractionState" : "extracted_with_value",
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "new",
- "value" : "Article Theme:"
- }
- },
- "es" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Tema del artículo:"
- }
- }
- }
- },
"o1h-xo-elW.title" : {
"comment" : "Class = \"NSMenuItem\"; title = \"Every 2 hours\"; ObjectID = \"o1h-xo-elW\";",
"extractionState" : "extracted_with_value",
@@ -283,18 +211,6 @@
}
}
},
- "Pkl-EA-Goa.title" : {
- "comment" : "Class = \"NSMenuItem\"; title = \"Default\"; ObjectID = \"Pkl-EA-Goa\";",
- "extractionState" : "extracted_with_value",
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "new",
- "value" : "Default"
- }
- }
- }
- },
"Qjt-qr-WER.title" : {
"comment" : "Class = \"NSMenuItem\"; title = \"Every hour\"; ObjectID = \"Qjt-qr-WER\";",
"extractionState" : "extracted_with_value",
@@ -313,42 +229,6 @@
}
}
},
- "qMe-6g-Vme.title" : {
- "comment" : "Class = \"NSMenuItem\"; title = \"Extra Large\"; ObjectID = \"qMe-6g-Vme\";",
- "extractionState" : "extracted_with_value",
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "new",
- "value" : "Extra Large"
- }
- },
- "es" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Extra grande"
- }
- }
- }
- },
- "roB-Mu-Ht7.title" : {
- "comment" : "Class = \"NSMenuItem\"; title = \"Small\"; ObjectID = \"roB-Mu-Ht7\";",
- "extractionState" : "extracted_with_value",
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "new",
- "value" : "Small"
- }
- },
- "es" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Pequeño"
- }
- }
- }
- },
"rZU-Tg-xwo.title" : {
"comment" : "Class = \"NSMenuItem\"; title = \"Every 30 minutes\"; ObjectID = \"rZU-Tg-xwo\";",
"extractionState" : "extracted_with_value",
@@ -492,42 +372,6 @@
}
}
}
- },
- "xQu-QV-91i.title" : {
- "comment" : "Class = \"NSTextFieldCell\"; title = \"Article Text Size:\"; ObjectID = \"xQu-QV-91i\";",
- "extractionState" : "extracted_with_value",
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "new",
- "value" : "Article Text Size:"
- }
- },
- "es" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Tamaño del texto:"
- }
- }
- }
- },
- "ySX-5i-SP1.title" : {
- "comment" : "Class = \"NSButtonCell\"; title = \"Open Themes Folder\"; ObjectID = \"ySX-5i-SP1\";",
- "extractionState" : "extracted_with_value",
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "new",
- "value" : "Open Themes Folder"
- }
- },
- "es" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Abrir carpeta de temas"
- }
- }
- }
}
},
"version" : "1.2"
diff --git a/Mac/Preferences/PreferencesWindowController.swift b/Mac/Preferences/PreferencesWindowController.swift
index 5a2312ede..b25ca6836 100644
--- a/Mac/Preferences/PreferencesWindowController.swift
+++ b/Mac/Preferences/PreferencesWindowController.swift
@@ -25,6 +25,14 @@ final class PreferencesWindowController: NSWindowController, NSToolbarDelegate {
name: NSLocalizedString("General", comment: "Preferences"),
image: Assets.Images.preferencesToolbarGeneral,
makeViewController: { GeneralPreferencesViewController() }),
+ PreferencesToolbarItemSpec(identifier: NSToolbarItem.Identifier("Appearance"),
+ name: NSLocalizedString("Appearance", comment: "Preferences"),
+ image: Assets.Images.preferencesToolbarAppearance,
+ makeViewController: { AppearancePreferencesViewController() }),
+ PreferencesToolbarItemSpec(identifier: NSToolbarItem.Identifier("Timeline"),
+ name: NSLocalizedString("Timeline", comment: "Timeline"),
+ image: Assets.Images.preferencesToolbarTimeline,
+ makeViewController: { TimelinePreferencesViewController() }),
PreferencesToolbarItemSpec(identifier: NSToolbarItem.Identifier("Accounts"),
name: NSLocalizedString("Accounts", comment: "Preferences"),
image: Assets.Images.preferencesToolbarAccounts,
diff --git a/Mac/Preferences/Timeline/Base.lproj/TimelinePreferencesView.xib b/Mac/Preferences/Timeline/Base.lproj/TimelinePreferencesView.xib
new file mode 100644
index 000000000..1969deecb
--- /dev/null
+++ b/Mac/Preferences/Timeline/Base.lproj/TimelinePreferencesView.xib
@@ -0,0 +1,318 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Mac/Preferences/Timeline/TimelinePreferencesViewController.swift b/Mac/Preferences/Timeline/TimelinePreferencesViewController.swift
new file mode 100644
index 000000000..22317eff3
--- /dev/null
+++ b/Mac/Preferences/Timeline/TimelinePreferencesViewController.swift
@@ -0,0 +1,200 @@
+//
+// TimelinePreferencesViewController.swift
+// NetNewsWire
+//
+// Created by Brent Simmons on 11/7/26.
+//
+
+import AppKit
+import RSCore
+import Images
+
+final class TimelinePreferencesViewController: NSViewController {
+
+ @IBOutlet var timelineIconsPopup: NSPopUpButton?
+ @IBOutlet var timelineIconSizePopup: NSPopUpButton?
+ @IBOutlet var timelineTitleAndSummaryButton: NSButton?
+ @IBOutlet var timelineNumberOfLinesPopup: NSPopUpButton?
+ @IBOutlet var timelineFullTitlesButton: NSButton?
+ @IBOutlet var timelineThumbnailsPopup: NSPopUpButton?
+ @IBOutlet var timelineTextSizePopup: NSPopUpButton?
+ @IBOutlet var timelineShowSeparatorsButton: NSButton?
+ @IBOutlet var timelineFadeReadArticlesButton: NSButton?
+ @IBOutlet var timelineFeedNameAndDateAboveTitleButton: NSButton?
+
+ convenience init() {
+ self.init(nibName: "TimelinePreferencesView", bundle: nil)
+ }
+
+ override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
+ super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
+ commonInit()
+ }
+
+ required init?(coder: NSCoder) {
+ super.init(coder: coder)
+ commonInit()
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+ view.sizeToFittingSize()
+ }
+
+ override func viewWillAppear() {
+ super.viewWillAppear()
+ updateTimelineFeedIconsPopup()
+ updateTimelineIconSizePopup()
+ updateTimelineThumbnailsPopup()
+ updateTimelineTextSizePopup()
+ updateTimelineRowsControls()
+ updateTimelineShowSeparatorsButton()
+ updateTimelineFadeReadArticlesButton()
+ updateTimelineFeedNameAndDateAboveTitleButton()
+ }
+
+ // MARK: - Notifications
+
+ @objc func handleTimelineFeedIconsDisplayDidChange(_ notification: Notification) {
+ updateTimelineFeedIconsPopup()
+ }
+
+ @objc func handleTimelineIconSizeDidChange(_ notification: Notification) {
+ updateTimelineIconSizePopup()
+ }
+
+ @objc func handleTimelineThumbnailsDisplayDidChange(_ notification: Notification) {
+ updateTimelineThumbnailsPopup()
+ }
+
+ @objc func handleTimelineTextSizeDidChange(_ notification: Notification) {
+ updateTimelineTextSizePopup()
+ }
+
+ @objc func handleTimelineNumberOfLinesDidChange(_ notification: Notification) {
+ updateTimelineRowsControls()
+ }
+
+ @objc func handleTimelineShowFullTitlesDidChange(_ notification: Notification) {
+ updateTimelineRowsControls()
+ }
+
+ @objc func handleTimelineShowSeparatorsDidChange(_ notification: Notification) {
+ updateTimelineShowSeparatorsButton()
+ }
+
+ @objc func handleTimelineFadeReadArticlesDidChange(_ notification: Notification) {
+ updateTimelineFadeReadArticlesButton()
+ }
+
+ @objc func handleTimelineFeedNameAndDateAboveTitleDidChange(_ notification: Notification) {
+ updateTimelineFeedNameAndDateAboveTitleButton()
+ }
+
+ // MARK: - Actions
+
+ @IBAction func timelineFeedIconsPopUpDidChange(_ sender: Any) {
+ guard let tag = timelineIconsPopup?.selectedTag(), let feedIconsDisplay = TimelineFeedIconsDisplay(rawValue: tag) else {
+ return
+ }
+ AppDefaults.timelineFeedIconsDisplay = feedIconsDisplay
+ }
+
+ @IBAction func timelineIconSizePopUpDidChange(_ sender: Any) {
+ guard let tag = timelineIconSizePopup?.selectedTag(), let iconSize = IconSize(rawValue: tag) else {
+ return
+ }
+ AppDefaults.timelineIconSize = iconSize
+ }
+
+ @IBAction func timelineThumbnailsPopUpDidChange(_ sender: Any) {
+ guard let tag = timelineThumbnailsPopup?.selectedTag(), let thumbnailsDisplay = TimelineThumbnailsDisplay(rawValue: tag) else {
+ return
+ }
+ AppDefaults.timelineThumbnailsDisplay = thumbnailsDisplay
+ }
+
+ @IBAction func timelineTextSizePopUpDidChange(_ sender: Any) {
+ guard let tag = timelineTextSizePopup?.selectedTag(), let textSize = TimelineTextSize(rawValue: tag) else {
+ return
+ }
+ AppDefaults.timelineTextSize = textSize
+ }
+
+ @IBAction func timelineNumberOfLinesPopUpDidChange(_ sender: Any) {
+ guard let numberOfLines = timelineNumberOfLinesPopup?.selectedTag() else {
+ return
+ }
+ AppDefaults.timelineNumberOfLines = numberOfLines
+ }
+
+ @IBAction func timelineRowsRadioButtonDidChange(_ sender: NSButton) {
+ AppDefaults.timelineShowFullTitles = sender === timelineFullTitlesButton
+ }
+
+ @IBAction func timelineShowSeparatorsDidChange(_ sender: NSButton) {
+ AppDefaults.timelineShowSeparators = sender.state == .on
+ }
+
+ @IBAction func timelineFadeReadArticlesDidChange(_ sender: NSButton) {
+ AppDefaults.timelineFadeReadArticles = sender.state == .on
+ }
+
+ @IBAction func timelineFeedNameAndDateAboveTitleDidChange(_ sender: NSButton) {
+ AppDefaults.timelineFeedNameAndDateAboveTitle = sender.state == .on
+ }
+}
+
+// MARK: - Private
+
+private extension TimelinePreferencesViewController {
+
+ func commonInit() {
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFeedIconsDisplayDidChange(_:)), name: .timelineFeedIconsDisplayDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineIconSizeDidChange(_:)), name: .timelineIconSizeDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineThumbnailsDisplayDidChange(_:)), name: .timelineThumbnailsDisplayDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineTextSizeDidChange(_:)), name: .timelineTextSizeDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineNumberOfLinesDidChange(_:)), name: .timelineNumberOfLinesDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineShowFullTitlesDidChange(_:)), name: .timelineShowFullTitlesDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineShowSeparatorsDidChange(_:)), name: .timelineShowSeparatorsDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFadeReadArticlesDidChange(_:)), name: .timelineFadeReadArticlesDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFeedNameAndDateAboveTitleDidChange(_:)), name: .timelineFeedNameAndDateAboveTitleDidChange, object: nil)
+ }
+
+ func updateTimelineFeedIconsPopup() {
+ timelineIconsPopup?.selectItem(withTag: AppDefaults.timelineFeedIconsDisplay.rawValue)
+ }
+
+ func updateTimelineIconSizePopup() {
+ timelineIconSizePopup?.selectItem(withTag: AppDefaults.timelineIconSize.rawValue)
+ }
+
+ func updateTimelineThumbnailsPopup() {
+ timelineThumbnailsPopup?.selectItem(withTag: AppDefaults.timelineThumbnailsDisplay.rawValue)
+ }
+
+ func updateTimelineTextSizePopup() {
+ timelineTextSizePopup?.selectItem(withTag: AppDefaults.timelineTextSize.rawValue)
+ }
+
+ /// The number of lines applies only to title and summary, so its popup is disabled with full titles.
+ func updateTimelineRowsControls() {
+ let showFullTitles = AppDefaults.timelineShowFullTitles
+ timelineTitleAndSummaryButton?.state = showFullTitles ? .off : .on
+ timelineFullTitlesButton?.state = showFullTitles ? .on : .off
+ timelineNumberOfLinesPopup?.selectItem(withTag: AppDefaults.timelineNumberOfLines)
+ timelineNumberOfLinesPopup?.isEnabled = !showFullTitles
+ }
+
+ func updateTimelineShowSeparatorsButton() {
+ timelineShowSeparatorsButton?.state = AppDefaults.timelineShowSeparators ? .on : .off
+ }
+
+ func updateTimelineFadeReadArticlesButton() {
+ timelineFadeReadArticlesButton?.state = AppDefaults.timelineFadeReadArticles ? .on : .off
+ }
+
+ func updateTimelineFeedNameAndDateAboveTitleButton() {
+ timelineFeedNameAndDateAboveTitleButton?.state = AppDefaults.timelineFeedNameAndDateAboveTitle ? .on : .off
+ }
+}
diff --git a/Mac/Preferences/Timeline/mul.lproj/TimelinePreferencesView.xcstrings b/Mac/Preferences/Timeline/mul.lproj/TimelinePreferencesView.xcstrings
new file mode 100644
index 000000000..53b08e0e9
--- /dev/null
+++ b/Mac/Preferences/Timeline/mul.lproj/TimelinePreferencesView.xcstrings
@@ -0,0 +1,414 @@
+{
+ "sourceLanguage" : "en",
+ "strings" : {
+ "tlB-fA-0c1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"Feed name and date above title\"; ObjectID = \"tlB-fA-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Feed name and date above title"
+ }
+ }
+ }
+ },
+ "tlB-fR-0c1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"Fade read articles\"; ObjectID = \"tlB-fR-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Fade read articles"
+ }
+ }
+ }
+ },
+ "tlB-sP-0c1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"Show separators\"; ObjectID = \"tlB-sP-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Show separators"
+ }
+ }
+ }
+ },
+ "tlL-fI-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Feed Icons:\"; ObjectID = \"tlL-fI-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Feed Icons:"
+ }
+ }
+ }
+ },
+ "tlL-fS-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Feed Icon Size:\"; ObjectID = \"tlL-fS-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Feed Icon Size:"
+ }
+ }
+ }
+ },
+ "tlL-ln-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"lines\"; ObjectID = \"tlL-ln-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "lines"
+ }
+ }
+ }
+ },
+ "tlL-nL-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Rows:\"; ObjectID = \"tlL-nL-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Rows:"
+ }
+ }
+ }
+ },
+ "tlL-tH-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Thumbnails:\"; ObjectID = \"tlL-tH-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Thumbnails:"
+ }
+ }
+ }
+ },
+ "tlL-tX-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Text Size:\"; ObjectID = \"tlL-tX-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Text Size:"
+ }
+ }
+ }
+ },
+ "tlM-fD-0m0.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Automatic\"; ObjectID = \"tlM-fD-0m0\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Automatic"
+ }
+ }
+ }
+ },
+ "tlM-fD-0m1.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Always\"; ObjectID = \"tlM-fD-0m1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Always"
+ }
+ }
+ }
+ },
+ "tlM-fD-0m2.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Never\"; ObjectID = \"tlM-fD-0m2\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Never"
+ }
+ }
+ }
+ },
+ "tlM-fS-0m1.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Small\"; ObjectID = \"tlM-fS-0m1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Small"
+ }
+ }
+ }
+ },
+ "tlM-fS-0m2.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Medium\"; ObjectID = \"tlM-fS-0m2\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Medium"
+ }
+ }
+ }
+ },
+ "tlM-fS-0m3.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Large\"; ObjectID = \"tlM-fS-0m3\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Large"
+ }
+ }
+ }
+ },
+ "tlM-nL-0m1.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"1\"; ObjectID = \"tlM-nL-0m1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "1"
+ }
+ }
+ }
+ },
+ "tlM-nL-0m2.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"2\"; ObjectID = \"tlM-nL-0m2\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "2"
+ }
+ }
+ }
+ },
+ "tlM-nL-0m3.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"3\"; ObjectID = \"tlM-nL-0m3\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "3"
+ }
+ }
+ }
+ },
+ "tlM-nL-0m4.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"4\"; ObjectID = \"tlM-nL-0m4\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "4"
+ }
+ }
+ }
+ },
+ "tlM-nL-0m5.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"5\"; ObjectID = \"tlM-nL-0m5\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "5"
+ }
+ }
+ }
+ },
+ "tlM-nL-0m6.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"6\"; ObjectID = \"tlM-nL-0m6\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "6"
+ }
+ }
+ }
+ },
+ "tlM-tS-0m0.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"None\"; ObjectID = \"tlM-tS-0m0\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "None"
+ }
+ }
+ }
+ },
+ "tlM-tS-0m1.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Small\"; ObjectID = \"tlM-tS-0m1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Small"
+ }
+ }
+ }
+ },
+ "tlM-tS-0m2.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Large\"; ObjectID = \"tlM-tS-0m2\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Large"
+ }
+ }
+ }
+ },
+ "tlM-tX-0m1.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Small\"; ObjectID = \"tlM-tX-0m1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Small"
+ }
+ }
+ }
+ },
+ "tlM-tX-0m2.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Medium\"; ObjectID = \"tlM-tX-0m2\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Medium"
+ }
+ }
+ }
+ },
+ "tlM-tX-0m3.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Large\"; ObjectID = \"tlM-tX-0m3\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Large"
+ }
+ }
+ }
+ },
+ "tlM-tX-0m4.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Extra Large\"; ObjectID = \"tlM-tX-0m4\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Extra Large"
+ }
+ }
+ }
+ },
+ "tlM-tX-0m5.title" : {
+ "comment" : "Class = \"NSMenuItem\"; title = \"Extra Extra Large\"; ObjectID = \"tlM-tX-0m5\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Extra Extra Large"
+ }
+ }
+ }
+ },
+ "tlN-cL-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Feed icon size, thumbnails, rows, and separators apply only to the standard layout.\"; ObjectID = \"tlN-cL-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Feed icon size, thumbnails, rows, and separators apply only to the standard layout."
+ }
+ }
+ }
+ },
+ "tlN-fD-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Automatic shows icons for folders, smart feeds, and authors with avatars.\"; ObjectID = \"tlN-fD-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Automatic shows icons for folders, smart feeds, and authors with avatars."
+ }
+ }
+ }
+ },
+ "tlN-fT-0c1.title" : {
+ "comment" : "Class = \"NSTextFieldCell\"; title = \"Shows the whole title, up to 12 lines.\"; ObjectID = \"tlN-fT-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Shows the whole title, up to 12 lines."
+ }
+ }
+ }
+ },
+ "tlR-fT-0c1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"Full title, no preview\"; ObjectID = \"tlR-fT-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Full title, no preview"
+ }
+ }
+ }
+ },
+ "tlR-tP-0c1.title" : {
+ "comment" : "Class = \"NSButtonCell\"; title = \"Title and preview, in\"; ObjectID = \"tlR-tP-0c1\";",
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Title and preview, in"
+ }
+ }
+ }
+ }
+ },
+ "version" : "1.2"
+}
\ No newline at end of file
diff --git a/Mac/Resources/Assets.xcassets/Account icon colors/Contents.json b/Mac/Resources/Assets.xcassets/Account icon colors/Contents.json
deleted file mode 100644
index 73c00596a..000000000
--- a/Mac/Resources/Assets.xcassets/Account icon colors/Contents.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/Resources/Assets.xcassets/Account icon colors/bazquxColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/Account icon colors/bazquxColor.colorset/Contents.json
deleted file mode 100644
index 7d310cf7a..000000000
--- a/Mac/Resources/Assets.xcassets/Account icon colors/bazquxColor.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.800",
- "green" : "0.600",
- "red" : "0.200"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.761",
- "green" : "0.561",
- "red" : "0.169"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/Resources/Assets.xcassets/Account icon colors/cloudkitColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/Account icon colors/cloudkitColor.colorset/Contents.json
deleted file mode 100644
index fcb0938d9..000000000
--- a/Mac/Resources/Assets.xcassets/Account icon colors/cloudkitColor.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.698",
- "green" : "0.682",
- "red" : "0.682"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.400",
- "green" : "0.388",
- "red" : "0.388"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/Resources/Assets.xcassets/Account icon colors/feedbinColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/Account icon colors/feedbinColor.colorset/Contents.json
deleted file mode 100644
index b62e9df29..000000000
--- a/Mac/Resources/Assets.xcassets/Account icon colors/feedbinColor.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.808",
- "green" : "0.369",
- "red" : "0.027"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.753",
- "green" : "0.271",
- "red" : "0.027"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/Resources/Assets.xcassets/Account icon colors/feedlyColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/Account icon colors/feedlyColor.colorset/Contents.json
deleted file mode 100644
index 57113378a..000000000
--- a/Mac/Resources/Assets.xcassets/Account icon colors/feedlyColor.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.298",
- "green" : "0.694",
- "red" : "0.169"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.220",
- "green" : "0.616",
- "red" : "0.090"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/Resources/Assets.xcassets/Account icon colors/freshRSSColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/Account icon colors/freshRSSColor.colorset/Contents.json
deleted file mode 100644
index 3451b43ef..000000000
--- a/Mac/Resources/Assets.xcassets/Account icon colors/freshRSSColor.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.741",
- "green" : "0.384",
- "red" : "0.000"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.663",
- "green" : "0.306",
- "red" : "0.004"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/Resources/Assets.xcassets/Account icon colors/inoreaderColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/Account icon colors/inoreaderColor.colorset/Contents.json
deleted file mode 100644
index 4ceea8871..000000000
--- a/Mac/Resources/Assets.xcassets/Account icon colors/inoreaderColor.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.780",
- "green" : "0.482",
- "red" : "0.004"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.702",
- "green" : "0.404",
- "red" : "0.004"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/Resources/Assets.xcassets/Account icon colors/localColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/Account icon colors/localColor.colorset/Contents.json
deleted file mode 100644
index 96b347187..000000000
--- a/Mac/Resources/Assets.xcassets/Account icon colors/localColor.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "1.000",
- "green" : "0.478",
- "red" : "0.000"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "1.000",
- "green" : "0.518",
- "red" : "0.039"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/Resources/Assets.xcassets/Account icon colors/newsblurColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/Account icon colors/newsblurColor.colorset/Contents.json
deleted file mode 100644
index 9d05aeb0b..000000000
--- a/Mac/Resources/Assets.xcassets/Account icon colors/newsblurColor.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.000",
- "green" : "0.584",
- "red" : "1.000"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.039",
- "green" : "0.624",
- "red" : "1.000"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/Resources/Assets.xcassets/Account icon colors/theoldreaderColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/Account icon colors/theoldreaderColor.colorset/Contents.json
deleted file mode 100644
index 2ac4d7409..000000000
--- a/Mac/Resources/Assets.xcassets/Account icon colors/theoldreaderColor.colorset/Contents.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.000",
- "green" : "0.145",
- "red" : "1.000"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "alpha" : "1.000",
- "blue" : "0.000",
- "green" : "0.067",
- "red" : "0.882"
- }
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/Resources/Assets.xcassets/DetailStatusBarBackground.colorset/Contents.json b/Mac/Resources/Assets.xcassets/DetailLinkOverlayBackground.colorset/Contents.json
similarity index 100%
rename from Mac/Resources/Assets.xcassets/DetailStatusBarBackground.colorset/Contents.json
rename to Mac/Resources/Assets.xcassets/DetailLinkOverlayBackground.colorset/Contents.json
diff --git a/Mac/Resources/Assets.xcassets/iconDarkBackgroundColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/iconDarkBackgroundColor.colorset/Contents.json
deleted file mode 100644
index de7a620f3..000000000
--- a/Mac/Resources/Assets.xcassets/iconDarkBackgroundColor.colorset/Contents.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "info" : {
- "version" : 1,
- "author" : "xcode"
- },
- "colors" : [
- {
- "idiom" : "universal",
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "red" : "56",
- "alpha" : "1.000",
- "blue" : "56",
- "green" : "56"
- }
- }
- }
- ]
-}
\ No newline at end of file
diff --git a/Mac/Resources/Assets.xcassets/iconLightBackgroundColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/iconLightBackgroundColor.colorset/Contents.json
deleted file mode 100644
index af234f435..000000000
--- a/Mac/Resources/Assets.xcassets/iconLightBackgroundColor.colorset/Contents.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "info" : {
- "version" : 1,
- "author" : "xcode"
- },
- "colors" : [
- {
- "idiom" : "universal",
- "color" : {
- "color-space" : "srgb",
- "components" : {
- "red" : "242",
- "alpha" : "1.000",
- "blue" : "242",
- "green" : "242"
- }
- }
- }
- ]
-}
diff --git a/Mac/Resources/Assets.xcassets/markAllRead.imageset/markAllRead.png b/Mac/Resources/Assets.xcassets/markAllRead.imageset/markAllRead.png
deleted file mode 100644
index bfd4d63b6..000000000
Binary files a/Mac/Resources/Assets.xcassets/markAllRead.imageset/markAllRead.png and /dev/null differ
diff --git a/Mac/Resources/Assets.xcassets/markAllRead.imageset/markAllRead@2x.png b/Mac/Resources/Assets.xcassets/markAllRead.imageset/markAllRead@2x.png
deleted file mode 100644
index 2782577d1..000000000
Binary files a/Mac/Resources/Assets.xcassets/markAllRead.imageset/markAllRead@2x.png and /dev/null differ
diff --git a/Mac/Resources/Assets.xcassets/preferencesToolbarExtensions.symbolset/Contents.json b/Mac/Resources/Assets.xcassets/preferencesToolbarAppearance.symbolset/Contents.json
similarity index 69%
rename from Mac/Resources/Assets.xcassets/preferencesToolbarExtensions.symbolset/Contents.json
rename to Mac/Resources/Assets.xcassets/preferencesToolbarAppearance.symbolset/Contents.json
index 1a4791180..c7c894bcb 100644
--- a/Mac/Resources/Assets.xcassets/preferencesToolbarExtensions.symbolset/Contents.json
+++ b/Mac/Resources/Assets.xcassets/preferencesToolbarAppearance.symbolset/Contents.json
@@ -5,7 +5,7 @@
},
"symbols" : [
{
- "filename" : "preferencesToolbarExtensions.svg",
+ "filename" : "preferencesToolbarAppearance.svg",
"idiom" : "universal"
}
]
diff --git a/Mac/Resources/Assets.xcassets/preferencesToolbarAppearance.symbolset/preferencesToolbarAppearance.svg b/Mac/Resources/Assets.xcassets/preferencesToolbarAppearance.symbolset/preferencesToolbarAppearance.svg
new file mode 100644
index 000000000..2834f1441
--- /dev/null
+++ b/Mac/Resources/Assets.xcassets/preferencesToolbarAppearance.symbolset/preferencesToolbarAppearance.svg
@@ -0,0 +1,156 @@
+
+
+ preferencesToolbarAppearance
+
+
+
+
+
+
+ Weight/Scale Variations
+
+
+ Ultralight
+
+
+ Thin
+
+
+ Light
+
+
+ Regular
+
+
+ Medium
+
+
+ Semibold
+
+
+ Bold
+
+
+ Heavy
+
+
+ Black
+
+
+
+
+
+
+
+
+
+
+
+
+ Design Variations
+
+
+ Symbols are supported in up to nine weights and three scales.
+
+
+ For optimal layout with text and other symbols, vertically align
+
+
+ symbols with the adjacent text.
+
+
+
+
+
+
+
+ Margins
+
+
+ Leading and trailing margins on the left and right side of each symbol
+
+
+ can be adjusted by modifying the width of the blue rectangles.
+
+
+ Modifications are automatically applied proportionally to all
+
+
+ scales and weights.
+
+
+
+
+
+ Exporting
+
+
+ Symbols should be outlined when exporting to ensure the
+
+
+ design is preserved when submitting to Xcode.
+
+
+ Template v.1.0
+
+
+ Generated from circle
+
+
+ Typeset at 100 points
+
+
+ Small
+
+
+ Medium
+
+
+ Large
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Mac/Resources/Assets.xcassets/preferencesToolbarExtensions.symbolset/preferencesToolbarExtensions.svg b/Mac/Resources/Assets.xcassets/preferencesToolbarExtensions.symbolset/preferencesToolbarExtensions.svg
deleted file mode 100644
index 90f8e2c60..000000000
--- a/Mac/Resources/Assets.xcassets/preferencesToolbarExtensions.symbolset/preferencesToolbarExtensions.svg
+++ /dev/null
@@ -1,161 +0,0 @@
-
-
-
-
-
-
-
-
- Weight/Scale Variations
- Ultralight
- Thin
- Light
- Regular
- Medium
- Semibold
- Bold
- Heavy
- Black
-
-
-
-
-
-
-
-
-
-
- Design Variations
- Symbols are supported in up to nine weights and three scales.
- For optimal layout with text and other symbols, vertically align
- symbols with the adjacent text.
-
-
-
-
-
- Margins
- Leading and trailing margins on the left and right side of each symbol
- can be adjusted by modifying the x-location of the margin guidelines.
- Modifications are automatically applied proportionally to all
- scales and weights.
-
-
-
- Exporting
- Symbols should be outlined when exporting to ensure the
- design is preserved when submitting to Xcode.
- Template v.2.0
- Requires Xcode 12 or greater
- Generated from bolt.fill.batteryblock
- Typeset at 100 points
- Small
- Medium
- Large
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Mac/Resources/Assets.xcassets/timelineSeparatorColor.colorset/Contents.json b/Mac/Resources/Assets.xcassets/timelineSeparatorColor.colorset/Contents.json
deleted file mode 100644
index 4821270ff..000000000
--- a/Mac/Resources/Assets.xcassets/timelineSeparatorColor.colorset/Contents.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "colors" : [
- {
- "color" : {
- "color-space" : "gray-gamma-22",
- "components" : {
- "alpha" : "1.000",
- "white" : "0.900"
- }
- },
- "idiom" : "universal"
- },
- {
- "appearances" : [
- {
- "appearance" : "luminosity",
- "value" : "dark"
- }
- ],
- "color" : {
- "platform" : "osx",
- "reference" : "quaternaryLabelColor"
- },
- "idiom" : "universal"
- }
- ],
- "info" : {
- "author" : "xcode",
- "version" : 1
- }
-}
diff --git a/Mac/SafariExtension/Info.plist b/Mac/SafariExtension/Info.plist
index 23df31598..de0b29d4a 100644
--- a/Mac/SafariExtension/Info.plist
+++ b/Mac/SafariExtension/Info.plist
@@ -3,7 +3,7 @@
AppGroup
- group.$(ORGANIZATION_IDENTIFIER).NetNewsWire-Evergreen
+ $(APP_GROUP_ID)
CFBundleDevelopmentRegion
$(DEVELOPMENT_LANGUAGE)
CFBundleDisplayName
diff --git a/Mac/Scripting/AppDelegate+Scriptability.swift b/Mac/Scripting/AppDelegate+Scriptability.swift
index f216471aa..f4bb1d082 100644
--- a/Mac/Scripting/AppDelegate+Scriptability.swift
+++ b/Mac/Scripting/AppDelegate+Scriptability.swift
@@ -66,6 +66,11 @@ extension AppDelegate: AppDelegateAppleEvents {
return
}
+ // Ignore other netnewswire: URLs rather than treating them as feeds
+ if urlString.lowercased().hasPrefix("netnewswire:") {
+ return
+ }
+
// Special case URL with specific scheme handler x-netnewswire-feed: intended to ensure we open
// it regardless of which news reader may be set as the default
let nnwScheme = "x-netnewswire-feed:"
diff --git a/Mac/ShareExtension/ShareViewController.swift b/Mac/ShareExtension/ShareViewController.swift
index bbb72839b..a8ce721ff 100644
--- a/Mac/ShareExtension/ShareViewController.swift
+++ b/Mac/ShareExtension/ShareViewController.swift
@@ -8,7 +8,7 @@
import AppKit
import UniformTypeIdentifiers
-import os
+import Synchronization
final class ShareViewController: NSViewController {
@IBOutlet var nameTextField: NSTextField!
@@ -17,7 +17,7 @@ final class ShareViewController: NSViewController {
private struct State: Sendable {
var url: URL?
}
- private let state = OSAllocatedUnfairLock(initialState: State())
+ private let state = Mutex(State())
nonisolated private var url: URL? {
get {
diff --git a/Modules/Account/.swiftpm/xcode/xcshareddata/xcschemes/Account.xcscheme b/Modules/Account/.swiftpm/xcode/xcshareddata/xcschemes/Account.xcscheme
index 8266675aa..2b26679f8 100644
--- a/Modules/Account/.swiftpm/xcode/xcshareddata/xcschemes/Account.xcscheme
+++ b/Modules/Account/.swiftpm/xcode/xcshareddata/xcschemes/Account.xcscheme
@@ -1,6 +1,6 @@
ParsedItem? {
markdown: nil,
summary: articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.summary] as? String,
imageURL: articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.imageURL] as? String,
+ thumbnailURL: nil,
bannerImageURL: articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.imageURL] as? String,
datePublished: articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.datePublished] as? Date,
dateModified: articleRecord[CloudKitArticlesZone.CloudKitArticle.Fields.dateModified] as? Date,
diff --git a/Modules/Account/Sources/Account/DataExtensions.swift b/Modules/Account/Sources/Account/DataExtensions.swift
index 60d64c7f6..a27bb8046 100644
--- a/Modules/Account/Sources/Account/DataExtensions.swift
+++ b/Modules/Account/Sources/Account/DataExtensions.swift
@@ -8,6 +8,7 @@
import Foundation
import Articles
+import RSCore
import RSParser
public extension Notification.Name {
@@ -61,4 +62,19 @@ public extension Article {
@MainActor var feed: Feed? {
return account?.existingFeed(withFeedID: feedID)
}
+
+ /// The URL that relative URLs in the article’s HTML resolve against: the article’s link,
+ /// else the feed’s home page, else the feed. Nil unless http or https.
+ @MainActor var baseURL: URL? {
+ guard let urlString = URL.encodeSpacesIfNeeded(rawLink)?.absoluteString ?? rawLink ?? feed?.homePageURL ?? feed?.url, var urlComponents = URLComponents(string: urlString) else {
+ return nil
+ }
+
+ // Can’t use url-with-fragment as base URL. The webview won’t load. See scripting.com/rss.xml for example.
+ urlComponents.fragment = nil
+ guard let url = urlComponents.url, url.scheme == "http" || url.scheme == "https" else {
+ return nil
+ }
+ return url
+ }
}
diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift
index b4b647964..a79b0e272 100644
--- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift
+++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift
@@ -82,6 +82,7 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable {
try await account.logActivity(kind: .refreshAll) {
try await refreshAccount(account)
try await refreshArticlesAndStatuses(account)
+ accountSettings?.lastRefreshCompletedDate = Date()
}
} catch {
refreshProgress.reset()
@@ -948,7 +949,6 @@ private extension FeedbinAccountDelegate {
guard let page else {
if let lastArticleFetch = updateFetchDate {
accountSettings?.lastArticleFetchStartTime = lastArticleFetch
- accountSettings?.lastRefreshCompletedDate = Date()
}
return
}
@@ -982,7 +982,7 @@ private extension FeedbinAccountDelegate {
let parsedItems: [ParsedItem] = entries.map { entry in
let authors = Set([ParsedAuthor(name: entry.authorName, url: entry.jsonFeed?.jsonFeedAuthor?.url, avatarURL: entry.jsonFeed?.jsonFeedAuthor?.avatarURL, emailAddress: nil)])
- return ParsedItem(syncServiceID: String(entry.articleID), uniqueID: String(entry.articleID), feedURL: String(entry.feedID), url: entry.url, externalURL: entry.jsonFeed?.jsonFeedExternalURL, title: entry.title, language: nil, contentHTML: entry.contentHTML, contentText: nil, markdown: nil, summary: entry.summary, imageURL: nil, bannerImageURL: nil, datePublished: entry.parsedDatePublished, dateModified: nil, authors: authors, tags: nil, attachments: nil)
+ return ParsedItem(syncServiceID: String(entry.articleID), uniqueID: String(entry.articleID), feedURL: String(entry.feedID), url: entry.url, externalURL: entry.jsonFeed?.jsonFeedExternalURL, title: entry.title, language: nil, contentHTML: entry.contentHTML, contentText: nil, markdown: nil, summary: entry.summary, imageURL: entry.imageURL, thumbnailURL: entry.thumbnailURL, bannerImageURL: nil, datePublished: entry.parsedDatePublished, dateModified: nil, authors: authors, tags: nil, attachments: entry.attachments)
}
return Set(parsedItems)
diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinEntry.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinEntry.swift
index 1232ed768..6c6cb9e56 100644
--- a/Modules/Account/Sources/Account/Feedbin/FeedbinEntry.swift
+++ b/Modules/Account/Sources/Account/Feedbin/FeedbinEntry.swift
@@ -21,6 +21,8 @@ final class FeedbinEntry: Decodable, Sendable {
let datePublished: String?
let dateArrived: String?
let jsonFeed: FeedbinEntryJSONFeed?
+ let images: FeedbinEntryImages?
+ let enclosure: FeedbinEntryEnclosure?
// Feedbin dates can't be decoded by the JSONDecoding 8601 decoding strategy. Feedbin
// requires a very specific date formatter to work and even then it fails occasionally.
@@ -33,6 +35,21 @@ final class FeedbinEntry: Decodable, Sendable {
return nil
}
+ var imageURL: String? {
+ images?.originalURL ?? enclosure?.itunesImageURL
+ }
+
+ var thumbnailURL: String? {
+ images?.thumbnail?.cdnURL
+ }
+
+ var attachments: [ParsedAttachment]? {
+ guard let attachment = enclosure?.parsedAttachment else {
+ return nil
+ }
+ return [attachment]
+ }
+
enum CodingKeys: String, CodingKey {
case articleID = "id"
case feedID = "feed_id"
@@ -44,6 +61,8 @@ final class FeedbinEntry: Decodable, Sendable {
case datePublished = "published"
case dateArrived = "created_at"
case jsonFeed = "json_feed"
+ case images = "images"
+ case enclosure = "enclosure"
}
}
@@ -80,3 +99,68 @@ struct FeedbinEntryJSONFeedAuthor: Decodable, Sendable {
case avatarURL = "avatar"
}
}
+
+struct FeedbinEntryImages: Decodable, Sendable {
+ let originalURL: String?
+ let thumbnail: FeedbinEntryThumbnail?
+
+ enum CodingKeys: String, CodingKey {
+ case originalURL = "original_url"
+ case thumbnail = "size_1"
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ originalURL = try? container.decodeIfPresent(String.self, forKey: .originalURL)
+ thumbnail = try? container.decodeIfPresent(FeedbinEntryThumbnail.self, forKey: .thumbnail)
+ }
+}
+
+/// Feedbin’s resized copy of the image, on its CDN.
+struct FeedbinEntryThumbnail: Decodable, Sendable {
+ let cdnURL: String?
+
+ enum CodingKeys: String, CodingKey {
+ case cdnURL = "cdn_url"
+ }
+}
+
+struct FeedbinEntryEnclosure: Decodable, Sendable {
+ let url: String?
+ let mimeType: String?
+ let length: String?
+ let itunesDuration: String?
+ let itunesImageURL: String?
+
+ var parsedAttachment: ParsedAttachment? {
+ guard let url else {
+ return nil
+ }
+ let durationInSeconds = ParsedAttachment.durationInSeconds(itunesDuration)
+ return ParsedAttachment(url: url, mimeType: mimeType, title: nil, sizeInBytes: sizeInBytes, durationInSeconds: durationInSeconds, width: nil, height: nil, medium: nil)
+ }
+
+ private var sizeInBytes: Int? {
+ guard let length, let sizeInBytes = Int(length), sizeInBytes > 0 else {
+ return nil
+ }
+ return sizeInBytes
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case url = "enclosure_url"
+ case mimeType = "enclosure_type"
+ case length = "enclosure_length"
+ case itunesDuration = "itunes_duration"
+ case itunesImageURL = "itunes_image"
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ url = try? container.decodeIfPresent(String.self, forKey: .url)
+ mimeType = try? container.decodeIfPresent(String.self, forKey: .mimeType)
+ length = try? container.decodeIfPresent(String.self, forKey: .length)
+ itunesDuration = try? container.decodeIfPresent(String.self, forKey: .itunesDuration)
+ itunesImageURL = try? container.decodeIfPresent(String.self, forKey: .itunesImageURL)
+ }
+}
diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyModel.swift b/Modules/Account/Sources/Account/Feedly/FeedlyModel.swift
index c7b072071..c8da94bb4 100644
--- a/Modules/Account/Sources/Account/Feedly/FeedlyModel.swift
+++ b/Modules/Account/Sources/Account/Feedly/FeedlyModel.swift
@@ -186,11 +186,21 @@ struct FeedlyEntry: Decodable, Sendable {
/// A list of media links (videos, images, sound etc) provided by the feed. Some entries do not have a summary or content, only a collection of media links.
let enclosure: [FeedlyLink]?
+
+ /// The image Feedly associates with the article.
+ let visual: FeedlyVisual?
+}
+
+struct FeedlyVisual: Decodable, Sendable {
+ /// Sometimes the literal `none`.
+ let url: String?
}
struct FeedlyEntryParser {
let entry: FeedlyEntry
+ private static let noVisualURL = "none"
+
private let rightToLeftTextSantizer = FeedlyRTLTextSanitizer()
var id: String {
@@ -240,7 +250,8 @@ struct FeedlyEntryParser {
// archive “now.” Publisher dates aren’t always reliable (per Feedly), so a
// future-dated article falls back to crawled rather than pinning itself to
// the top of a date-sorted timeline.
- if let published = entry.published, published <= entry.crawled {
+ // Not <=, which is back-deployed and crashes on iOS 27.2 betas.
+ if let published = entry.published, published < entry.crawled {
return published
}
return entry.crawled
@@ -265,12 +276,19 @@ struct FeedlyEntryParser {
return Set(labels)
}
- var attachments: Set? {
+ var attachments: [ParsedAttachment]? {
guard let enclosure = entry.enclosure, !enclosure.isEmpty else {
return nil
}
- let attachments = enclosure.compactMap { ParsedAttachment(url: $0.href, mimeType: $0.type, title: nil, sizeInBytes: nil, durationInSeconds: nil) }
- return attachments.isEmpty ? nil : Set(attachments)
+ let attachments = enclosure.compactMap { ParsedAttachment(url: $0.href, mimeType: $0.type, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: nil) }
+ return attachments.isEmpty ? nil : attachments
+ }
+
+ var imageURL: String? {
+ guard let url = entry.visual?.url, !url.isEmpty, url != Self.noVisualURL else {
+ return nil
+ }
+ return url
}
var parsedItemRepresentation: ParsedItem? {
@@ -289,7 +307,8 @@ struct FeedlyEntryParser {
contentText: contentText,
markdown: nil,
summary: summary,
- imageURL: nil,
+ imageURL: imageURL,
+ thumbnailURL: nil,
bannerImageURL: nil,
datePublished: datePublished,
dateModified: dateModified,
diff --git a/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift b/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift
index a87f95d05..df0c48c04 100644
--- a/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift
+++ b/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift
@@ -9,6 +9,7 @@
import Foundation
@preconcurrency import AuthenticationServices
import os
+import Synchronization
import ActivityLog
import RSCore
@@ -48,7 +49,7 @@ struct UnableToStartASWebAuthenticationSessionError: LocalizedError, Sendable {
private struct State: @unchecked Sendable {
var presentationAnchor: ASPresentationAnchor?
}
- private let state = OSAllocatedUnfairLock(initialState: State())
+ private let state = Mutex(State())
var presentationAnchor: ASPresentationAnchor? {
get {
@@ -84,7 +85,7 @@ public final class OAuthAccountAuthorizationOperation: MainThreadOperation, @unc
private struct SessionState: @unchecked Sendable {
var session: ASWebAuthenticationSession?
}
- private let sessionState = OSAllocatedUnfairLock(initialState: SessionState())
+ private let sessionState = Mutex(SessionState())
private let accountType: AccountType
private let oauthClient: OAuthAuthorizationClient
private let anchorProvider = PresentationAnchorProvider()
diff --git a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift
index dfbe8637a..56f821537 100644
--- a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift
+++ b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift
@@ -237,7 +237,6 @@ import os
guard let hashes = hashes, !hashes.isEmpty else {
if let lastArticleFetch = updateFetchDate {
self.accountSettings?.lastArticleFetchStartTime = lastArticleFetch
- self.accountSettings?.lastRefreshCompletedDate = Date()
}
return
}
@@ -260,7 +259,7 @@ import os
let parsedItems: [ParsedItem] = stories.map { story in
let author = Set([ParsedAuthor(name: story.authorName, url: nil, avatarURL: nil, emailAddress: nil)])
- return ParsedItem(syncServiceID: story.storyID, uniqueID: String(story.storyID), feedURL: String(story.feedID), url: story.url, externalURL: nil, title: story.title, language: nil, contentHTML: story.contentHTML, contentText: nil, markdown: nil, summary: nil, imageURL: story.imageURL, bannerImageURL: nil, datePublished: story.datePublished, dateModified: nil, authors: author, tags: Set(story.tags ?? []), attachments: nil)
+ return ParsedItem(syncServiceID: story.storyID, uniqueID: String(story.storyID), feedURL: String(story.feedID), url: story.url, externalURL: nil, title: story.title, language: nil, contentHTML: story.contentHTML, contentText: nil, markdown: nil, summary: nil, imageURL: story.imageURL, thumbnailURL: story.thumbnailURL, bannerImageURL: nil, datePublished: story.datePublished, dateModified: nil, authors: author, tags: Set(story.tags ?? []), attachments: nil)
}
return Set(parsedItems)
diff --git a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift
index 4434f6ac3..22e490b3b 100644
--- a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift
+++ b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift
@@ -264,7 +264,8 @@ import Secrets
guard let datePublished = $0.datePublished, let since else {
return true
}
- return datePublished >= since
+ // Not >=, which is back-deployed and crashes on iOS 27.2 betas.
+ return datePublished > since
}
let feedIDsAndItems = Dictionary(grouping: parsedItems, by: { item in item.feedURL }).mapValues {
Set($0)
diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift
index 536031902..2179a61d7 100644
--- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift
+++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift
@@ -152,6 +152,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
await refreshMissingArticles(account)
refreshProgress.reset()
+ accountSettings?.lastRefreshCompletedDate = Date()
}
} catch where rateLimiter.isRateLimitError(error) {
refreshProgress.reset()
@@ -1152,13 +1153,14 @@ private extension ReaderAPIAccountDelegate {
contentText: nil,
markdown: nil,
summary: entry.summary.content,
- imageURL: nil,
+ imageURL: entry.imageURL,
+ thumbnailURL: nil,
bannerImageURL: nil,
datePublished: entry.parseDatePublished(),
dateModified: nil,
authors: authors,
tags: nil,
- attachments: nil)
+ attachments: entry.attachments)
}
return Set(parsedItems)
diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift
index a0efd18a0..17b40a23a 100644
--- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift
+++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift
@@ -518,7 +518,6 @@ struct ReaderAPIUsageLimits {
guard let continuation else {
if type == .allForAccount {
self.accountSettings?.lastArticleFetchStartTime = dateInfo?.date
- self.accountSettings?.lastRefreshCompletedDate = Date()
}
return itemIDs
}
diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIEntry.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIEntry.swift
index c7d423653..76edfb058 100644
--- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIEntry.swift
+++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIEntry.swift
@@ -59,6 +59,16 @@ struct ReaderAPIEntry: Codable, Sendable {
let alternates: [ReaderAPIAlternateLocation]?
let categories: [String]
let origin: ReaderAPIEntryOrigin
+ let enclosures: [ReaderAPIEnclosure]?
+
+ var attachments: [ParsedAttachment]? {
+ let attachments = enclosures?.compactMap { $0.parsedAttachment } ?? []
+ return attachments.isEmpty ? nil : attachments
+ }
+
+ var imageURL: String? {
+ enclosures?.first { $0.isImage }?.url
+ }
enum CodingKeys: String, CodingKey {
case articleID = "id"
@@ -71,6 +81,7 @@ struct ReaderAPIEntry: Codable, Sendable {
case crawledTimestamp = "crawlTimeMsec"
case origin = "origin"
case timestampUsec = "timestampUsec"
+ case enclosures = "enclosure"
}
func parseDatePublished() -> Date? {
@@ -120,6 +131,67 @@ struct ReaderAPIAlternateLocation: Codable, Sendable {
}
}
+/// `type` is a MIME type, or a bare `image`, `audio`, or `video` (FreshRSS).
+struct ReaderAPIEnclosure: Codable, Sendable {
+ let url: String?
+ let type: String?
+ let length: Int?
+
+ var parsedAttachment: ParsedAttachment? {
+ guard let url else {
+ return nil
+ }
+ return ParsedAttachment(url: url, mimeType: mimeType, title: nil, sizeInBytes: sizeInBytes, durationInSeconds: nil, width: nil, height: nil, medium: medium)
+ }
+
+ var isImage: Bool {
+ medium == .image || mimeType?.lowercased().hasPrefix("image/") == true
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case url = "href"
+ case type
+ case length
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ url = try? container.decodeIfPresent(String.self, forKey: .url)
+ type = try? container.decodeIfPresent(String.self, forKey: .type)
+ if let length = try? container.decodeIfPresent(Int.self, forKey: .length) {
+ self.length = length
+ } else if let lengthString = try? container.decodeIfPresent(String.self, forKey: .length) {
+ self.length = Int(lengthString)
+ } else {
+ self.length = nil
+ }
+ }
+}
+
+private extension ReaderAPIEnclosure {
+
+ var sizeInBytes: Int? {
+ guard let length, length > 0 else {
+ return nil
+ }
+ return length
+ }
+
+ var mimeType: String? {
+ guard let type, type.contains("/") else {
+ return nil
+ }
+ return type
+ }
+
+ var medium: ParsedAttachment.Medium? {
+ guard mimeType == nil else {
+ return nil
+ }
+ return ParsedAttachment.Medium(mediaRSSValue: type)
+ }
+}
+
struct ReaderAPIEntryOrigin: Codable, Sendable {
let streamId: String?
let title: String?
diff --git a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinEntryTests.swift b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinEntryTests.swift
new file mode 100644
index 000000000..9d65387b4
--- /dev/null
+++ b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinEntryTests.swift
@@ -0,0 +1,55 @@
+//
+// FeedbinEntryTests.swift
+// AccountTests
+//
+// Created by Brent Simmons on 10/23/26.
+//
+
+import Foundation
+import Testing
+@testable import Account
+
+struct FeedbinEntryTests {
+
+ @Test func imagesAndEnclosure() throws {
+ // Fields from the Feedbin API docs for mode=extended.
+ let json = """
+ {
+ "id": 2077,
+ "feed_id": 135,
+ "title": "Objective-C Runtime Releases",
+ "url": "http://mjtsai.com/blog/2013/02/02/objective-c-runtime-releases/",
+ "author": "Michael Tsai",
+ "content": "Bavarious created a GitHub repository.
",
+ "summary": "Bavarious created a GitHub repository.",
+ "published": "2013-02-03T01:00:19.000000Z",
+ "created_at": "2013-02-04T01:00:19.127893Z",
+ "images": {
+ "original_url": "http://example.com/image.jpg",
+ "size_1": {
+ "cdn_url": "https://images.feedbinusercontent.com/image.jpg",
+ "width": 542,
+ "height": 304
+ }
+ },
+ "enclosure": {
+ "enclosure_url": "http://example.com/episode.mp3",
+ "enclosure_type": "audio/mpeg",
+ "enclosure_length": "54947132",
+ "itunes_duration": "01:54:09",
+ "itunes_image": "http://example.com/artwork.jpg"
+ }
+ }
+ """
+ let entry = try JSONDecoder().decode(FeedbinEntry.self, from: Data(json.utf8))
+
+ #expect(entry.imageURL == "http://example.com/image.jpg")
+ #expect(entry.thumbnailURL == "https://images.feedbinusercontent.com/image.jpg")
+
+ let attachment = try #require(entry.attachments?.first)
+ #expect(attachment.url == "http://example.com/episode.mp3")
+ #expect(attachment.mimeType == "audio/mpeg")
+ #expect(attachment.sizeInBytes == 54947132)
+ #expect(attachment.durationInSeconds == 6849)
+ }
+}
diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryParserTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryParserTests.swift
index a919b71c0..22bd30975 100644
--- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryParserTests.swift
+++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryParserTests.swift
@@ -34,7 +34,8 @@ import XCTest
unread: false,
tags: tags,
categories: nil,
- enclosure: nil)
+ enclosure: nil,
+ visual: nil)
let parser = FeedlyEntryParser(entry: entry)
@@ -93,7 +94,8 @@ import XCTest
unread: false,
tags: nil,
categories: nil,
- enclosure: nil)
+ enclosure: nil,
+ visual: nil)
let parser = FeedlyEntryParser(entry: entry)
@@ -122,7 +124,8 @@ import XCTest
unread: false,
tags: nil,
categories: nil,
- enclosure: nil)
+ enclosure: nil,
+ visual: nil)
let parser = FeedlyEntryParser(entry: entry)
@@ -146,7 +149,8 @@ import XCTest
unread: false,
tags: nil,
categories: nil,
- enclosure: nil)
+ enclosure: nil,
+ visual: nil)
let parser = FeedlyEntryParser(entry: entry)
@@ -170,7 +174,8 @@ import XCTest
unread: false,
tags: nil,
categories: nil,
- enclosure: nil)
+ enclosure: nil,
+ visual: nil)
let parser = FeedlyEntryParser(entry: entry)
@@ -209,7 +214,8 @@ import XCTest
unread: false,
tags: nil,
categories: nil,
- enclosure: nil)
+ enclosure: nil,
+ visual: nil)
let parser = FeedlyEntryParser(entry: entry)
@@ -231,6 +237,7 @@ import XCTest
unread: false,
tags: nil,
categories: nil,
- enclosure: nil)
+ enclosure: nil,
+ visual: nil)
}
}
diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryVisualTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryVisualTests.swift
new file mode 100644
index 000000000..10fb9c901
--- /dev/null
+++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyEntryVisualTests.swift
@@ -0,0 +1,28 @@
+//
+// FeedlyEntryVisualTests.swift
+// AccountTests
+//
+// Created by Brent Simmons on 10/23/26.
+//
+
+import Foundation
+import Testing
+@testable import Account
+
+struct FeedlyEntryVisualTests {
+
+ @Test func visualIsImageURL() {
+ // From feedly_macintosh_initial.json.
+ let url = "https://cdn.vox-cdn.com/thumbor/BkK9uk46u1ujrjGO0Jav3PCQ3g0=/0x225:5363x3800/1310x873/cdn.vox-cdn.com/uploads/chorus_image/image/59608177/PIA22227_full.0.jpg"
+ #expect(FeedlyEntryParser(entry: makeEntry(visualURL: url)).parsedItemRepresentation?.imageURL == url)
+ #expect(FeedlyEntryParser(entry: makeEntry(visualURL: "none")).parsedItemRepresentation?.imageURL == nil)
+ }
+}
+
+private extension FeedlyEntryVisualTests {
+
+ func makeEntry(visualURL: String) -> FeedlyEntry {
+ let origin = FeedlyOrigin(title: "The Verge", streamID: "feed/http://www.theverge.com/rss/full.xml", htmlURL: nil)
+ return FeedlyEntry(id: "entry", title: nil, content: nil, summary: nil, author: nil, crawled: .distantPast, recrawled: nil, published: nil, origin: origin, canonical: nil, alternate: nil, unread: true, tags: nil, categories: nil, enclosure: nil, visual: FeedlyVisual(url: visualURL))
+ }
+}
diff --git a/Modules/Account/Tests/AccountTests/ReaderAPI/ReaderAPIEntryTests.swift b/Modules/Account/Tests/AccountTests/ReaderAPI/ReaderAPIEntryTests.swift
index 19a98a44c..cf8aff5b4 100644
--- a/Modules/Account/Tests/AccountTests/ReaderAPI/ReaderAPIEntryTests.swift
+++ b/Modules/Account/Tests/AccountTests/ReaderAPI/ReaderAPIEntryTests.swift
@@ -50,6 +50,33 @@ struct ReaderAPIEntryTests {
}
}
+ @Test func enclosures() throws {
+ // From FreshRSS’s toGReader: a MIME type, or a bare medium.
+ let json = """
+ {
+ "id": "tag:google.com,2005:reader/item/00058b10ce338909",
+ "summary": {},
+ "categories": [],
+ "origin": {},
+ "enclosure": [
+ {"href": "https://example.com/episode.mp3", "type": "audio/mpeg", "length": 54947132},
+ {"href": "https://example.com/cover.jpg", "type": "image"}
+ ]
+ }
+ """
+ let entry = try JSONDecoder().decode(ReaderAPIEntry.self, from: Data(json.utf8))
+
+ #expect(entry.imageURL == "https://example.com/cover.jpg")
+
+ let attachments = try #require(entry.attachments)
+ let audio = try #require(attachments.first { $0.url == "https://example.com/episode.mp3" })
+ #expect(audio.mimeType == "audio/mpeg")
+ #expect(audio.sizeInBytes == 54947132)
+ let image = try #require(attachments.first { $0.url == "https://example.com/cover.jpg" })
+ #expect(image.mimeType == nil)
+ #expect(image.medium == .image)
+ }
+
private func makeEntry(articleID: String) throws -> ReaderAPIEntry {
let json = "{\"id\":\"\(articleID)\",\"summary\":{},\"categories\":[],\"origin\":{}}"
return try JSONDecoder().decode(ReaderAPIEntry.self, from: Data(json.utf8))
diff --git a/Modules/ActivityLog/Package.swift b/Modules/ActivityLog/Package.swift
index 351a57383..d98ab0f11 100644
--- a/Modules/ActivityLog/Package.swift
+++ b/Modules/ActivityLog/Package.swift
@@ -4,7 +4,7 @@ import PackageDescription
let package = Package(
name: "ActivityLog",
defaultLocalization: "en",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(
name: "ActivityLog",
diff --git a/Modules/ActivityLog/Sources/ActivityLog/ActivityKind.swift b/Modules/ActivityLog/Sources/ActivityLog/ActivityKind.swift
index 579cc39f1..f4b345f78 100644
--- a/Modules/ActivityLog/Sources/ActivityLog/ActivityKind.swift
+++ b/Modules/ActivityLog/Sources/ActivityLog/ActivityKind.swift
@@ -63,6 +63,7 @@ public enum ActivityKind: Sendable, Hashable {
case downloadFavicon(faviconURL: String)
case downloadAvatar(avatarURL: String)
case downloadHTMLMetadata(urlString: String)
+ case downloadThumbnail(imageURL: String)
/// Localized description for activity kinds that don't carry a URL to display separately.
/// Returns nil for the URL-bearing cases — each caller renders its own primary + URL form.
@@ -124,7 +125,7 @@ public enum ActivityKind: Sendable, Hashable {
return NSLocalizedString("Validating credentials", bundle: .module, comment: "Activity kind")
case .exportOPML:
return NSLocalizedString("Exporting OPML", bundle: .module, comment: "Activity kind")
- case .refreshFeedContent, .findFeed, .fetchFeedCandidate, .downloadFeedImage, .downloadFavicon, .downloadAvatar, .downloadHTMLMetadata:
+ case .refreshFeedContent, .findFeed, .fetchFeedCandidate, .downloadFeedImage, .downloadFavicon, .downloadAvatar, .downloadHTMLMetadata, .downloadThumbnail:
return nil
}
}
@@ -157,6 +158,9 @@ public enum ActivityKind: Sendable, Hashable {
case .downloadHTMLMetadata(let urlString):
let format = NSLocalizedString("Downloading metadata %@", bundle: .module, comment: "Activity kind — downloading HTML metadata — %@ is the URL")
return String(format: format, urlString)
+ case .downloadThumbnail(let imageURL):
+ let format = NSLocalizedString("Downloading thumbnail %@", bundle: .module, comment: "Activity kind — downloading a timeline thumbnail — %@ is the URL")
+ return String(format: format, imageURL)
default:
return ""
}
diff --git a/Modules/ActivityLog/Sources/ActivityLog/ActivityOwner.swift b/Modules/ActivityLog/Sources/ActivityLog/ActivityOwner.swift
index cc9181714..5d04e2565 100644
--- a/Modules/ActivityLog/Sources/ActivityLog/ActivityOwner.swift
+++ b/Modules/ActivityLog/Sources/ActivityLog/ActivityOwner.swift
@@ -16,6 +16,7 @@ public enum ActivityOwner: Sendable, Hashable {
case faviconDownloader
case avatarDownloader
case htmlMetadataDownloader
+ case thumbnailDownloader
public var displayName: String {
switch self {
@@ -33,6 +34,8 @@ public enum ActivityOwner: Sendable, Hashable {
return NSLocalizedString("Avatars", bundle: .module, comment: "Activity owner name")
case .htmlMetadataDownloader:
return NSLocalizedString("HTML Metadata", bundle: .module, comment: "Activity owner name")
+ case .thumbnailDownloader:
+ return NSLocalizedString("Thumbnails", bundle: .module, comment: "Activity owner name")
}
}
@@ -46,7 +49,8 @@ public enum ActivityOwner: Sendable, Hashable {
(.feedImageDownloader, .feedImageDownloader),
(.faviconDownloader, .faviconDownloader),
(.avatarDownloader, .avatarDownloader),
- (.htmlMetadataDownloader, .htmlMetadataDownloader):
+ (.htmlMetadataDownloader, .htmlMetadataDownloader),
+ (.thumbnailDownloader, .thumbnailDownloader):
return true
case (.account(let lhsID, _), .account(let rhsID, _)):
return lhsID == rhsID
@@ -72,6 +76,8 @@ public enum ActivityOwner: Sendable, Hashable {
hasher.combine(5)
case .htmlMetadataDownloader:
hasher.combine(6)
+ case .thumbnailDownloader:
+ hasher.combine(7)
}
}
}
diff --git a/Modules/ActivityLog/Sources/ActivityLog/Resources/Localizable.xcstrings b/Modules/ActivityLog/Sources/ActivityLog/Resources/Localizable.xcstrings
index 06854be9d..ae3cd720a 100644
--- a/Modules/ActivityLog/Sources/ActivityLog/Resources/Localizable.xcstrings
+++ b/Modules/ActivityLog/Sources/ActivityLog/Resources/Localizable.xcstrings
@@ -57,6 +57,9 @@
"Downloading metadata %@" : {
"comment" : "Activity kind — downloading HTML metadata — %@ is the URL"
},
+ "Downloading thumbnail %@" : {
+ "comment" : "Activity kind — downloading a timeline thumbnail — %@ is the URL"
+ },
"Exporting OPML" : {
"comment" : "Activity kind",
"localizations" : {
@@ -307,6 +310,9 @@
}
}
},
+ "Thumbnails" : {
+ "comment" : "Activity owner name"
+ },
"Vacuuming database" : {
"comment" : "Activity kind",
"localizations" : {
diff --git a/Modules/Articles/.swiftpm/xcode/xcshareddata/xcschemes/Articles.xcscheme b/Modules/Articles/.swiftpm/xcode/xcshareddata/xcschemes/Articles.xcscheme
index 2697ec127..a5c8abed3 100644
--- a/Modules/Articles/.swiftpm/xcode/xcshareddata/xcschemes/Articles.xcscheme
+++ b/Modules/Articles/.swiftpm/xcode/xcshareddata/xcschemes/Articles.xcscheme
@@ -1,6 +1,6 @@
?
+ public let attachments: [Attachment]?
public let status: ArticleStatus
- public init(accountID: String, articleID: String?, feedID: String, uniqueID: String, title: String?, contentHTML: String?, contentText: String?, markdown: String?, url: String?, externalURL: String?, summary: String?, imageURL: String?, datePublished: Date?, dateModified: Date?, authors: Set?, status: ArticleStatus) {
+ public init(accountID: String, articleID: String?, feedID: String, uniqueID: String, title: String?, contentHTML: String?, contentText: String?, markdown: String?, url: String?, externalURL: String?, summary: String?, imageURL: String?, thumbnailURL: String?, datePublished: Date?, dateModified: Date?, authors: Set?, attachments: [Attachment]?, status: ArticleStatus) {
self.accountID = accountID
self.feedID = feedID
self.uniqueID = uniqueID
@@ -41,9 +43,11 @@ public final class Article: Hashable, Sendable {
self.rawExternalLink = externalURL
self.summary = summary
self.rawImageLink = imageURL
+ self.rawThumbnailLink = thumbnailURL
self.datePublished = datePublished
self.dateModified = dateModified
self.authors = authors
+ self.attachments = attachments
self.status = status
if let articleID = articleID {
@@ -66,7 +70,7 @@ public final class Article: Hashable, Sendable {
// MARK: - Equatable
static public func ==(lhs: Article, rhs: Article) -> Bool {
- return lhs.articleID == rhs.articleID && lhs.accountID == rhs.accountID && lhs.feedID == rhs.feedID && lhs.uniqueID == rhs.uniqueID && lhs.title == rhs.title && lhs.contentHTML == rhs.contentHTML && lhs.contentText == rhs.contentText && lhs.markdown == rhs.markdown && lhs.rawLink == rhs.rawLink && lhs.rawExternalLink == rhs.rawExternalLink && lhs.summary == rhs.summary && lhs.rawImageLink == rhs.rawImageLink && lhs.datePublished == rhs.datePublished && lhs.dateModified == rhs.dateModified && lhs.authors == rhs.authors
+ return lhs.articleID == rhs.articleID && lhs.accountID == rhs.accountID && lhs.feedID == rhs.feedID && lhs.uniqueID == rhs.uniqueID && lhs.title == rhs.title && lhs.contentHTML == rhs.contentHTML && lhs.contentText == rhs.contentText && lhs.markdown == rhs.markdown && lhs.rawLink == rhs.rawLink && lhs.rawExternalLink == rhs.rawExternalLink && lhs.summary == rhs.summary && lhs.rawImageLink == rhs.rawImageLink && lhs.rawThumbnailLink == rhs.rawThumbnailLink && lhs.datePublished == rhs.datePublished && lhs.dateModified == rhs.dateModified && lhs.authors == rhs.authors && lhs.attachments == rhs.attachments
}
}
diff --git a/Modules/Articles/Sources/Articles/ArticleStatus.swift b/Modules/Articles/Sources/Articles/ArticleStatus.swift
index 5e664a8bc..0bcc10aae 100644
--- a/Modules/Articles/Sources/Articles/ArticleStatus.swift
+++ b/Modules/Articles/Sources/Articles/ArticleStatus.swift
@@ -7,7 +7,7 @@
//
import Foundation
-import os
+import Synchronization
public final class ArticleStatus: Hashable, Sendable {
@@ -27,7 +27,7 @@ public final class ArticleStatus: Hashable, Sendable {
var starred: Bool
}
- private let state: OSAllocatedUnfairLock
+ private let state: Mutex
public var read: Bool {
get {
@@ -49,7 +49,7 @@ public final class ArticleStatus: Hashable, Sendable {
public init(articleID: String, read: Bool, starred: Bool, dateArrived: Date) {
self.articleID = articleID
- self.state = OSAllocatedUnfairLock(initialState: State(read: read, starred: starred))
+ self.state = Mutex(State(read: read, starred: starred))
self.dateArrived = dateArrived
}
diff --git a/Modules/Articles/Sources/Articles/Attachment.swift b/Modules/Articles/Sources/Articles/Attachment.swift
new file mode 100644
index 000000000..70cf70f14
--- /dev/null
+++ b/Modules/Articles/Sources/Articles/Attachment.swift
@@ -0,0 +1,112 @@
+//
+// Attachment.swift
+// Articles
+//
+// Created by Brent Simmons on 10/23/26.
+//
+
+import Foundation
+
+/// An enclosure or Media RSS item: audio, video, image, or other file attached to an article.
+public struct Attachment: Codable, Hashable, Sendable {
+
+ /// Raw values are stored in the database, so don’t remove or rename cases.
+ public enum Medium: String, Codable, Sendable {
+ case image
+ case audio
+ case video
+ case document
+ case executable
+ }
+
+ public let url: String
+ public let mimeType: String?
+ public let title: String?
+ public let sizeInBytes: Int?
+ public let durationInSeconds: Int?
+ public let width: Int?
+ public let height: Int?
+ public let medium: Medium?
+
+ public init?(url: String, mimeType: String?, title: String?, sizeInBytes: Int?, durationInSeconds: Int?, width: Int?, height: Int?, medium: Medium?) {
+ if url.isEmpty {
+ return nil
+ }
+
+ self.url = url
+ self.mimeType = mimeType
+ self.title = title
+ self.sizeInBytes = sizeInBytes
+ self.durationInSeconds = durationInSeconds
+ self.width = width
+ self.height = height
+ self.medium = medium
+ }
+
+ public static func attachmentsWithJSON(_ data: Data) -> [Attachment]? {
+ let decoder = JSONDecoder()
+ do {
+ return try decoder.decode([Attachment].self, from: data)
+ } catch {
+ assertionFailure("JSON representation of Attachment array could not be decoded, error: \(error)")
+ }
+ return nil
+ }
+}
+
+// MARK: - Display
+
+extension Attachment {
+
+ private static let audioFileExtensions: Set = ["mp3", "m4a", "aac", "wav", "ogg", "oga", "opus", "flac"]
+ private static let videoFileExtensions: Set = ["mp4", "m4v", "mov", "webm"]
+ private static let imageFileExtensions: Set = ["jpg", "jpeg", "png", "gif", "webp", "heic", "avif"]
+
+ /// How the article view shows this attachment: `.audio`, `.video`, or `.image`.
+ /// Nil for anything else. Checks the MIME type, then `medium`, then the URL’s file extension.
+ public var displayMedium: Medium? {
+ if let mimeType = mimeType?.lowercased() {
+ if mimeType.hasPrefix("audio/") {
+ return .audio
+ }
+ if mimeType.hasPrefix("video/") {
+ return .video
+ }
+ if mimeType.hasPrefix("image/") {
+ return .image
+ }
+ }
+
+ if medium == .audio || medium == .video || medium == .image {
+ return medium
+ }
+
+ guard let pathExtension = URL(string: url)?.pathExtension.lowercased(), !pathExtension.isEmpty else {
+ return nil
+ }
+ if Self.audioFileExtensions.contains(pathExtension) {
+ return .audio
+ }
+ if Self.videoFileExtensions.contains(pathExtension) {
+ return .video
+ }
+ if Self.imageFileExtensions.contains(pathExtension) {
+ return .image
+ }
+ return nil
+ }
+}
+
+extension Array where Element == Attachment {
+
+ public func json() -> String? {
+ let encoder = JSONEncoder()
+ do {
+ let jsonData = try encoder.encode(self)
+ return String(data: jsonData, encoding: .utf8)
+ } catch {
+ assertionFailure("JSON representation of Attachment array could not be encoded: \(self) error: \(error)")
+ }
+ return nil
+ }
+}
diff --git a/Modules/Articles/Sources/Articles/AuthorCache.swift b/Modules/Articles/Sources/Articles/AuthorCache.swift
index 1db82143e..323ed267a 100644
--- a/Modules/Articles/Sources/Articles/AuthorCache.swift
+++ b/Modules/Articles/Sources/Articles/AuthorCache.swift
@@ -6,7 +6,7 @@
//
import Foundation
-import os
+import Synchronization
import RSCore
/// Caches `Author` values by `authorID` so articles by the same author share
@@ -15,7 +15,7 @@ public final class AuthorCache: Sendable {
public static let shared = AuthorCache()
- private let cache = OSAllocatedUnfairLock<[String: Author]>(initialState: [:])
+ private let cache = Mutex<[String: Author]>([:])
init() {
if !Platform.isRunningUnitTests {
diff --git a/Modules/Articles/Tests/ArticlesTests/AttachmentTests.swift b/Modules/Articles/Tests/ArticlesTests/AttachmentTests.swift
new file mode 100644
index 000000000..b6a5a54f1
--- /dev/null
+++ b/Modules/Articles/Tests/ArticlesTests/AttachmentTests.swift
@@ -0,0 +1,31 @@
+//
+// AttachmentTests.swift
+// ArticlesTests
+//
+// Created by Brent Simmons on 10/23/26.
+//
+
+import Foundation
+import Testing
+import Articles
+
+@Suite struct AttachmentTests {
+
+ @Test func displayMedium() throws {
+ // Podcast enclosure served as a generic binary type: the file extension decides.
+ let podcast = try #require(Attachment(url: "https://example.com/episode.mp3", mimeType: "application/octet-stream", title: nil, sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: nil))
+ #expect(podcast.displayMedium == .audio)
+
+ // atp.fm items with no type attribute, only medium.
+ let atp = try #require(Attachment(url: "http://traffic.libsyn.com/atpfm/atp309.mp3", mimeType: nil, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: .audio))
+ #expect(atp.displayMedium == .audio)
+
+ // cloudblog.rss image with no type or medium.
+ let image = try #require(Attachment(url: "https://storage.googleapis.com/gweb-cloudblog-publish/images/shadow_IT.max-600x600.png", mimeType: nil, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: 540, height: 540, medium: nil))
+ #expect(image.displayMedium == .image)
+
+ // YouTube’s Flash player URL isn’t displayable.
+ let youTube = try #require(Attachment(url: "https://www.youtube.com/v/abcdefghijk?version=3", mimeType: "application/x-shockwave-flash", title: nil, sizeInBytes: nil, durationInSeconds: nil, width: 640, height: 390, medium: nil))
+ #expect(youTube.displayMedium == nil)
+ }
+}
diff --git a/Modules/ArticlesDatabase/Package.swift b/Modules/ArticlesDatabase/Package.swift
index 52f245708..5a38eeec0 100644
--- a/Modules/ArticlesDatabase/Package.swift
+++ b/Modules/ArticlesDatabase/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
let package = Package(
name: "ArticlesDatabase",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(
name: "ArticlesDatabase",
diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift
index ac1b069f0..2b3474b5c 100644
--- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift
+++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift
@@ -83,6 +83,14 @@ public struct ArticleCounts: Sendable {
Self.logger.debug("ArticlesDatabase: adding authors column \(accountID, privacy: .public)")
database.executeStatements("ALTER TABLE articles add column authors TEXT;")
}
+ if !self.articlesTable.containsColumn("attachments", in: database) {
+ Self.logger.debug("ArticlesDatabase: adding attachments column \(accountID, privacy: .public)")
+ database.executeStatements("ALTER TABLE articles add column attachments TEXT;")
+ }
+ if !self.articlesTable.containsColumn("thumbnailURL", in: database) {
+ Self.logger.debug("ArticlesDatabase: adding thumbnailURL column \(accountID, privacy: .public)")
+ database.executeStatements("ALTER TABLE articles add column thumbnailURL TEXT;")
+ }
database.executeStatements("CREATE INDEX if not EXISTS articles_searchRowID on articles(searchRowID);")
database.executeStatements("DROP TABLE if EXISTS tags;DROP INDEX if EXISTS tags_tagName_index;DROP INDEX if EXISTS articles_feedID_index;DROP INDEX if EXISTS statuses_read_index;DROP TABLE if EXISTS attachments;DROP TABLE if EXISTS attachmentsLookup;")
}
@@ -432,7 +440,7 @@ public struct ArticleCounts: Sendable {
private extension ArticlesDatabase {
static let tableCreationStatements = """
- CREATE TABLE if not EXISTS articles (articleID TEXT NOT NULL PRIMARY KEY, feedID TEXT NOT NULL, uniqueID TEXT NOT NULL, title TEXT, contentHTML TEXT, contentText TEXT, markdown TEXT, url TEXT, externalURL TEXT, summary TEXT, imageURL TEXT, bannerImageURL TEXT, datePublished DATE, dateModified DATE, searchRowID INTEGER, authors TEXT);
+ CREATE TABLE if not EXISTS articles (articleID TEXT NOT NULL PRIMARY KEY, feedID TEXT NOT NULL, uniqueID TEXT NOT NULL, title TEXT, contentHTML TEXT, contentText TEXT, markdown TEXT, url TEXT, externalURL TEXT, summary TEXT, imageURL TEXT, bannerImageURL TEXT, datePublished DATE, dateModified DATE, searchRowID INTEGER, authors TEXT, attachments TEXT, thumbnailURL TEXT);
CREATE TABLE if not EXISTS statuses (articleID TEXT NOT NULL PRIMARY KEY, read BOOL NOT NULL DEFAULT 0, starred BOOL NOT NULL DEFAULT 0, dateArrived DATE NOT NULL DEFAULT 0);
diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift
index 961d53444..555430122 100644
--- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift
+++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift
@@ -12,6 +12,7 @@ import RSCore
import RSDatabase
import RSDatabaseObjC
import RSParser
+import Synchronization
import Articles
final class ArticlesTable: DatabaseTable, Sendable {
@@ -22,7 +23,7 @@ final class ArticlesTable: DatabaseTable, Sendable {
private let statusesTable: StatusesTable
private let searchTable: SearchTable
private let retentionStyle: ArticlesDatabase.RetentionStyle
- private let articlesCache = OSAllocatedUnfairLock(initialState: [String: Article]())
+ private let articlesCache = Mutex([String: Article]())
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ArticlesTable")
private static let signposter = OSSignposter(subsystem: Logger.nnwSubsystem, category: .pointsOfInterest)
diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Constants.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Constants.swift
index 7435a1d7f..e04f5fdbe 100644
--- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Constants.swift
+++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Constants.swift
@@ -30,9 +30,11 @@ struct DatabaseKey {
static let externalURL = "externalURL"
static let summary = "summary"
static let imageURL = "imageURL"
+ static let thumbnailURL = "thumbnailURL"
static let datePublished = "datePublished"
static let dateModified = "dateModified"
static let authors = "authors"
+ static let attachments = "attachments"
static let searchRowID = "searchRowID"
// ArticleStatus
diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift
index 6d76ebdfb..8aa1c3a11 100644
--- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift
+++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Article+Database.swift
@@ -36,11 +36,13 @@ extension Article {
let externalURL = row.swiftString(forColumn: DatabaseKey.externalURL)
let summary = row.swiftString(forColumn: DatabaseKey.summary)
let imageURL = row.swiftString(forColumn: DatabaseKey.imageURL)
+ let thumbnailURL = row.swiftString(forColumn: DatabaseKey.thumbnailURL)
let datePublished = row.date(forColumn: DatabaseKey.datePublished)
let dateModified = row.date(forColumn: DatabaseKey.dateModified)
let authors = Self.authorsFromRow(row)
+ let attachments = Self.attachmentsFromRow(row)
- self.init(accountID: accountID, articleID: articleID, feedID: feedID, uniqueID: uniqueID, title: title, contentHTML: contentHTML, contentText: contentText, markdown: markdown, url: url, externalURL: externalURL, summary: summary, imageURL: imageURL, datePublished: datePublished, dateModified: dateModified, authors: authors, status: status)
+ self.init(accountID: accountID, articleID: articleID, feedID: feedID, uniqueID: uniqueID, title: title, contentHTML: contentHTML, contentText: contentText, markdown: markdown, url: url, externalURL: externalURL, summary: summary, imageURL: imageURL, thumbnailURL: thumbnailURL, datePublished: datePublished, dateModified: dateModified, authors: authors, attachments: attachments, status: status)
}
private static func authorsFromRow(_ row: FMResultSet) -> Set? {
@@ -50,8 +52,16 @@ extension Article {
return Author.authorsWithJSON(data)
}
+ private static func attachmentsFromRow(_ row: FMResultSet) -> [Attachment]? {
+ guard let json = row.swiftString(forColumn: DatabaseKey.attachments), !json.isEmpty, let data = json.data(using: .utf8) else {
+ return nil
+ }
+ return Attachment.attachmentsWithJSON(data)
+ }
+
convenience init(parsedItem: ParsedItem, maximumDateAllowed: Date, accountID: String, feedID: String, status: ArticleStatus) {
let authors = Author.authorsWithParsedAuthors(parsedItem.authors)
+ let attachments = Attachment.attachmentsWithParsedAttachments(parsedItem.attachments)
// Deal with future datePublished and dateModified dates.
var datePublished = parsedItem.datePublished
@@ -67,7 +77,7 @@ extension Article {
dateModified = nil
}
- self.init(accountID: accountID, articleID: parsedItem.syncServiceID, feedID: feedID, uniqueID: parsedItem.uniqueID, title: parsedItem.title, contentHTML: parsedItem.contentHTML, contentText: parsedItem.contentText, markdown: parsedItem.markdown, url: parsedItem.url, externalURL: parsedItem.externalURL, summary: parsedItem.summary, imageURL: parsedItem.imageURL, datePublished: datePublished, dateModified: dateModified, authors: authors, status: status)
+ self.init(accountID: accountID, articleID: parsedItem.syncServiceID, feedID: feedID, uniqueID: parsedItem.uniqueID, title: parsedItem.title, contentHTML: parsedItem.contentHTML, contentText: parsedItem.contentText, markdown: parsedItem.markdown, url: parsedItem.url, externalURL: parsedItem.externalURL, summary: parsedItem.summary, imageURL: parsedItem.imageURL, thumbnailURL: parsedItem.thumbnailURL, datePublished: datePublished, dateModified: dateModified, authors: authors, attachments: attachments, status: status)
}
private func addPossibleStringChangeWithKeyPath(_ comparisonKeyPath: KeyPath, _ otherArticle: Article, _ key: String, _ dictionary: inout DatabaseDictionary) {
@@ -98,6 +108,7 @@ extension Article {
addPossibleStringChangeWithKeyPath(\Article.rawExternalLink, existingArticle, DatabaseKey.externalURL, &d)
addPossibleStringChangeWithKeyPath(\Article.summary, existingArticle, DatabaseKey.summary, &d)
addPossibleStringChangeWithKeyPath(\Article.rawImageLink, existingArticle, DatabaseKey.imageURL, &d)
+ addPossibleStringChangeWithKeyPath(\Article.rawThumbnailLink, existingArticle, DatabaseKey.thumbnailURL, &d)
if authors != existingArticle.authors {
if let authors, !authors.isEmpty, let json = authors.json() {
@@ -107,6 +118,14 @@ extension Article {
}
}
+ if attachments != existingArticle.attachments {
+ if let attachments, !attachments.isEmpty, let json = attachments.json() {
+ d[DatabaseKey.attachments] = json
+ } else {
+ d[DatabaseKey.attachments] = ""
+ }
+ }
+
// If updated versions of dates are nil, and we have existing dates, keep the existing dates.
// This is data that’s good to have, and it’s likely that a feed removing dates is doing so in error.
if datePublished != existingArticle.datePublished {
@@ -184,6 +203,9 @@ extension Article {
if let rawImageLink = rawImageLink {
d[DatabaseKey.imageURL] = rawImageLink
}
+ if let rawThumbnailLink {
+ d[DatabaseKey.thumbnailURL] = rawThumbnailLink
+ }
if let datePublished = datePublished {
d[DatabaseKey.datePublished] = datePublished
}
@@ -193,6 +215,9 @@ extension Article {
if let authors, !authors.isEmpty, let json = authors.json() {
d[DatabaseKey.authors] = json
}
+ if let attachments, !attachments.isEmpty, let json = attachments.json() {
+ d[DatabaseKey.attachments] = json
+ }
return d
}
}
diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Attachment+Database.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Attachment+Database.swift
new file mode 100644
index 000000000..d203e05af
--- /dev/null
+++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Extensions/Attachment+Database.swift
@@ -0,0 +1,39 @@
+//
+// Attachment+Database.swift
+// ArticlesDatabase
+//
+// Created by Brent Simmons on 10/23/26.
+//
+
+import Foundation
+import Articles
+import RSParser
+
+extension Attachment {
+
+ init?(parsedAttachment: ParsedAttachment) {
+ let medium = Medium(parsedMedium: parsedAttachment.medium)
+ self.init(url: parsedAttachment.url, mimeType: parsedAttachment.mimeType, title: parsedAttachment.title, sizeInBytes: parsedAttachment.sizeInBytes, durationInSeconds: parsedAttachment.durationInSeconds, width: parsedAttachment.width, height: parsedAttachment.height, medium: medium)
+ }
+
+ /// Keeps the order, dropping repeats of a URL.
+ public static func attachmentsWithParsedAttachments(_ parsedAttachments: [ParsedAttachment]?) -> [Attachment]? {
+ guard let parsedAttachments else {
+ return nil
+ }
+
+ var urls = Set()
+ let attachments = parsedAttachments.filter { urls.insert($0.url).inserted }.compactMap { Attachment(parsedAttachment: $0) }
+ return attachments.isEmpty ? nil : attachments
+ }
+}
+
+extension Attachment.Medium {
+
+ init?(parsedMedium: ParsedAttachment.Medium?) {
+ guard let parsedMedium else {
+ return nil
+ }
+ self.init(rawValue: parsedMedium.rawValue)
+ }
+}
diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift
index 47afcede1..937676e39 100644
--- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift
+++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift
@@ -11,6 +11,7 @@ import os
import RSCore
import RSDatabase
import RSDatabaseObjC
+import Synchronization
import Articles
// Article->ArticleStatus is a to-one relationship.
@@ -325,7 +326,7 @@ private final class StatusCache: Sendable {
var dictionary = [String: ArticleStatus]()
}
- private let state = OSAllocatedUnfairLock(initialState: State())
+ private let state = Mutex(State())
func addStatusIfNotCached(_ status: ArticleStatus) {
addIfNotCached(Set([status]))
diff --git a/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/ArticleUpdateTests.swift b/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/ArticleUpdateTests.swift
index 0f12c9539..b7edac9de 100644
--- a/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/ArticleUpdateTests.swift
+++ b/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/ArticleUpdateTests.swift
@@ -28,7 +28,7 @@ import ArticlesDatabase
}
@Test func identicalUpdateReportsNoChanges() async {
- let item = parsedItem(title: "Title", markdown: nil)
+ let item = parsedItem(title: "Title", markdown: nil, attachments: nil, thumbnailURL: nil)
let firstChanges = await database.updateAsync(parsedItems: [item], feedID: feedID, deleteOlder: false)
#expect(firstChanges.new?.count == 1)
@@ -39,10 +39,10 @@ import ArticlesDatabase
}
@Test func markdownChangePersists() async {
- let original = parsedItem(title: "Title", markdown: "one")
+ let original = parsedItem(title: "Title", markdown: "one", attachments: nil, thumbnailURL: nil)
_ = await database.updateAsync(parsedItems: [original], feedID: feedID, deleteOlder: false)
- let edited = parsedItem(title: "Title", markdown: "two")
+ let edited = parsedItem(title: "Title", markdown: "two", attachments: nil, thumbnailURL: nil)
let changes = await database.updateAsync(parsedItems: [edited], feedID: feedID, deleteOlder: false)
#expect(changes.updated?.count == 1)
@@ -52,10 +52,10 @@ import ArticlesDatabase
}
@Test func clearedFieldStopsReportingAsUpdated() async {
- let withTitle = parsedItem(title: "Title", markdown: nil)
+ let withTitle = parsedItem(title: "Title", markdown: nil, attachments: nil, thumbnailURL: nil)
_ = await database.updateAsync(parsedItems: [withTitle], feedID: feedID, deleteOlder: false)
- let withoutTitle = parsedItem(title: nil, markdown: nil)
+ let withoutTitle = parsedItem(title: nil, markdown: nil, attachments: nil, thumbnailURL: nil)
let clearingChanges = await database.updateAsync(parsedItems: [withoutTitle], feedID: feedID, deleteOlder: false)
#expect(clearingChanges.updated?.count == 1)
@@ -74,18 +74,83 @@ import ArticlesDatabase
#expect(one != two)
#expect(one == article(markdown: "one"))
}
+
+ @Test func attachmentsPersist() async throws {
+ let item = parsedItem(title: "Title", markdown: nil, attachments: [try episodeAttachment(durationInSeconds: 3600)], thumbnailURL: nil)
+ _ = await database.updateAsync(parsedItems: [item], feedID: feedID, deleteOlder: false)
+
+ database.emptyCaches()
+ let fetched = await database.fetchArticlesAsync(feedID: feedID).first
+ let attachment = try #require(fetched?.attachments?.first)
+ #expect(fetched?.attachments?.count == 1)
+ #expect(attachment.url == "https://example.com/episode.mp3")
+ #expect(attachment.mimeType == "audio/mpeg")
+ #expect(attachment.sizeInBytes == 12345678)
+ #expect(attachment.durationInSeconds == 3600)
+ #expect(attachment.medium == .audio)
+ }
+
+ @Test func attachmentOnlyChangeIsUpdate() async throws {
+ let original = parsedItem(title: "Title", markdown: nil, attachments: [try episodeAttachment(durationInSeconds: nil)], thumbnailURL: nil)
+ _ = await database.updateAsync(parsedItems: [original], feedID: feedID, deleteOlder: false)
+
+ database.emptyCaches()
+ let edited = parsedItem(title: "Title", markdown: nil, attachments: [try episodeAttachment(durationInSeconds: 3600)], thumbnailURL: nil)
+ let changes = await database.updateAsync(parsedItems: [edited], feedID: feedID, deleteOlder: false)
+ #expect(changes.updated?.count == 1)
+
+ database.emptyCaches()
+ let fetched = await database.fetchArticlesAsync(feedID: feedID).first
+ #expect(fetched?.attachments?.first?.durationInSeconds == 3600)
+ }
+
+ @Test func clearedAttachmentsStopReportingAsUpdated() async throws {
+ let withAttachments = parsedItem(title: "Title", markdown: nil, attachments: [try episodeAttachment(durationInSeconds: 3600)], thumbnailURL: nil)
+ _ = await database.updateAsync(parsedItems: [withAttachments], feedID: feedID, deleteOlder: false)
+
+ database.emptyCaches()
+ let withoutAttachments = parsedItem(title: "Title", markdown: nil, attachments: nil, thumbnailURL: nil)
+ let clearingChanges = await database.updateAsync(parsedItems: [withoutAttachments], feedID: feedID, deleteOlder: false)
+ #expect(clearingChanges.updated?.count == 1)
+
+ database.emptyCaches()
+ let fetched = await database.fetchArticlesAsync(feedID: feedID).first
+ #expect(fetched?.attachments == nil)
+
+ database.emptyCaches()
+ let repeatChanges = await database.updateAsync(parsedItems: [withoutAttachments], feedID: feedID, deleteOlder: false)
+ #expect(repeatChanges.updated == nil)
+ }
+
+ @Test func thumbnailChangePersists() async {
+ let original = parsedItem(title: "Title", markdown: nil, attachments: nil, thumbnailURL: "https://example.com/small.jpg")
+ _ = await database.updateAsync(parsedItems: [original], feedID: feedID, deleteOlder: false)
+
+ database.emptyCaches()
+ let edited = parsedItem(title: "Title", markdown: nil, attachments: nil, thumbnailURL: "https://example.com/small-2.jpg")
+ let changes = await database.updateAsync(parsedItems: [edited], feedID: feedID, deleteOlder: false)
+ #expect(changes.updated?.count == 1)
+
+ database.emptyCaches()
+ let fetched = await database.fetchArticlesAsync(feedID: feedID).first
+ #expect(fetched?.rawThumbnailLink == "https://example.com/small-2.jpg")
+ }
}
// MARK: - Helpers
private extension ArticleUpdateTests {
- func parsedItem(title: String?, markdown: String?) -> ParsedItem {
- ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedID, url: "https://example.com/\(uniqueID)", externalURL: nil, title: title, language: nil, contentHTML: "Test
", contentText: nil, markdown: markdown, summary: nil, imageURL: nil, bannerImageURL: nil, datePublished: Date(timeIntervalSince1970: 0), dateModified: nil, authors: nil, tags: nil, attachments: nil)
+ func parsedItem(title: String?, markdown: String?, attachments: [ParsedAttachment]?, thumbnailURL: String?) -> ParsedItem {
+ ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedID, url: "https://example.com/\(uniqueID)", externalURL: nil, title: title, language: nil, contentHTML: "Test
", contentText: nil, markdown: markdown, summary: nil, imageURL: nil, thumbnailURL: thumbnailURL, bannerImageURL: nil, datePublished: Date(timeIntervalSince1970: 0), dateModified: nil, authors: nil, tags: nil, attachments: attachments)
}
func article(markdown: String?) -> Article {
let status = ArticleStatus(articleID: "article1", read: false, starred: false, dateArrived: Date(timeIntervalSince1970: 0))
- return Article(accountID: "test", articleID: "article1", feedID: feedID, uniqueID: uniqueID, title: "Title", contentHTML: "Test
", contentText: nil, markdown: markdown, url: nil, externalURL: nil, summary: nil, imageURL: nil, datePublished: nil, dateModified: nil, authors: nil, status: status)
+ return Article(accountID: "test", articleID: "article1", feedID: feedID, uniqueID: uniqueID, title: "Title", contentHTML: "Test
", contentText: nil, markdown: markdown, url: nil, externalURL: nil, summary: nil, imageURL: nil, thumbnailURL: nil, datePublished: nil, dateModified: nil, authors: nil, attachments: nil, status: status)
+ }
+
+ func episodeAttachment(durationInSeconds: Int?) throws -> ParsedAttachment {
+ try #require(ParsedAttachment(url: "https://example.com/episode.mp3", mimeType: "audio/mpeg", title: nil, sizeInBytes: 12345678, durationInSeconds: durationInSeconds, width: nil, height: nil, medium: .audio))
}
}
diff --git a/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/StatusDivergenceTests.swift b/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/StatusDivergenceTests.swift
index 601b4d64e..bb22e5d7a 100644
--- a/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/StatusDivergenceTests.swift
+++ b/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/StatusDivergenceTests.swift
@@ -136,6 +136,6 @@ private extension StatusDivergenceTests {
}
func parsedItem(uniqueID: String) -> ParsedItem {
- ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedID, url: "https://example.com/\(uniqueID)", externalURL: nil, title: "Article \(uniqueID)", language: nil, contentHTML: "Test
", contentText: nil, markdown: nil, summary: nil, imageURL: nil, bannerImageURL: nil, datePublished: Date(), dateModified: nil, authors: nil, tags: nil, attachments: nil)
+ ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedID, url: "https://example.com/\(uniqueID)", externalURL: nil, title: "Article \(uniqueID)", language: nil, contentHTML: "Test
", contentText: nil, markdown: nil, summary: nil, imageURL: nil, thumbnailURL: nil, bannerImageURL: nil, datePublished: Date(), dateModified: nil, authors: nil, tags: nil, attachments: nil)
}
}
diff --git a/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/TodayQueriesTests.swift b/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/TodayQueriesTests.swift
index f73591ab8..54ca10011 100644
--- a/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/TodayQueriesTests.swift
+++ b/Modules/ArticlesDatabase/Tests/ArticlesDatabaseTests/TodayQueriesTests.swift
@@ -114,6 +114,6 @@ private extension TodayQueriesTests {
}
func parsedItem(uniqueID: String, feedID: String, datePublished: Date?) -> ParsedItem {
- ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedID, url: "https://example.com/\(uniqueID)", externalURL: nil, title: "Article \(uniqueID)", language: nil, contentHTML: "Test
", contentText: nil, markdown: nil, summary: nil, imageURL: nil, bannerImageURL: nil, datePublished: datePublished, dateModified: nil, authors: nil, tags: nil, attachments: nil)
+ ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedID, url: "https://example.com/\(uniqueID)", externalURL: nil, title: "Article \(uniqueID)", language: nil, contentHTML: "Test
", contentText: nil, markdown: nil, summary: nil, imageURL: nil, thumbnailURL: nil, bannerImageURL: nil, datePublished: datePublished, dateModified: nil, authors: nil, tags: nil, attachments: nil)
}
}
diff --git a/Modules/CloudKitSync/Package.swift b/Modules/CloudKitSync/Package.swift
index c1cbdfac7..7414c4c76 100644
--- a/Modules/CloudKitSync/Package.swift
+++ b/Modules/CloudKitSync/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
let package = Package(
name: "CloudKitSync",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(
name: "CloudKitSync",
diff --git a/Modules/ErrorLog/Package.swift b/Modules/ErrorLog/Package.swift
index 2115c45f8..7cd0bc69a 100644
--- a/Modules/ErrorLog/Package.swift
+++ b/Modules/ErrorLog/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
let package = Package(
name: "ErrorLog",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(
name: "ErrorLog",
diff --git a/Modules/FeedFinder/Package.swift b/Modules/FeedFinder/Package.swift
index 6b22b0a0b..aef783a1f 100644
--- a/Modules/FeedFinder/Package.swift
+++ b/Modules/FeedFinder/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
let package = Package(
name: "FeedFinder",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(
name: "FeedFinder",
diff --git a/Modules/HTMLMetadata/Package.swift b/Modules/HTMLMetadata/Package.swift
index c11e76c38..fc055c7fd 100644
--- a/Modules/HTMLMetadata/Package.swift
+++ b/Modules/HTMLMetadata/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
let package = Package(
name: "HTMLMetadata",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(
name: "HTMLMetadata",
diff --git a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift
index 5e14cfc35..f2f4841ae 100644
--- a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift
+++ b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift
@@ -11,6 +11,7 @@ import os
import RSCore
import RSParser
import RSWeb
+import Synchronization
import ActivityLog
nonisolated public final class HTMLMetadataDownloader: Sendable {
@@ -21,10 +22,14 @@ nonisolated public final class HTMLMetadataDownloader: Sendable {
private static let hoursBetweenAttempts = 3
- private let attemptDates = OSAllocatedUnfairLock(initialState: [String: Date]())
+ private let attemptDates = Mutex([String: Date]())
/// In-memory mirror so `cachedMetadata(for:)` can answer synchronously.
- private let cache = OSAllocatedUnfairLock(initialState: [String: HTMLMetadataRecord]())
+ private let cache = Mutex([String: HTMLMetadataRecord]())
+
+ /// Icon lookups ask for metadata on every cell configure, so a URL isn’t looked up again
+ /// while its lookup runs, or after it found nothing, until `cache` is emptied.
+ private let urlsLookedUp = Mutex(Set())
init() {
NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
@@ -32,11 +37,11 @@ nonisolated public final class HTMLMetadataDownloader: Sendable {
}
@objc func handleAppDidGoToBackground(_ notification: Notification) {
- cache.withLock { $0.removeAll() }
+ emptyCache()
}
@objc func handleLowMemory(_ notification: Notification) {
- cache.withLock { $0.removeAll() }
+ emptyCache()
}
/// Returns cached metadata synchronously, or kicks off a fetch and returns nil.
@@ -66,7 +71,15 @@ nonisolated private extension HTMLMetadataDownloader {
SpecialCase.urlStringContainSpecialCase(urlString, specialCasesToSkip)
}
+ func emptyCache() {
+ cache.withLock { $0.removeAll() }
+ urlsLookedUp.withLock { $0.removeAll() }
+ }
+
func fetchAndDownloadIfNeeded(_ url: String) {
+ guard urlsLookedUp.withLock({ $0.insert(url).inserted }) else {
+ return
+ }
Task { @MainActor in
if let record = await HTMLMetadataDatabase.shared.cachedRecord(for: url) {
cacheRecord(record)
@@ -82,6 +95,26 @@ nonisolated private extension HTMLMetadataDownloader {
}
}
+ /// A redirect between `example.com` and `www.example.com` stays on the same host.
+ static func isRedirectToAnotherHost(from url: URL, to responseURL: URL) -> Bool {
+ guard let host = hostIgnoringWWW(url), let responseHost = hostIgnoringWWW(responseURL) else {
+ return false
+ }
+ return host != responseHost
+ }
+
+ static func hostIgnoringWWW(_ url: URL) -> String? {
+ guard let host = url.host()?.lowercased() else {
+ return nil
+ }
+ return host.hasPrefix("www.") ? String(host.dropFirst(4)) : host
+ }
+
+ /// Off the main thread, since a home page can be a few megabytes.
+ @concurrent static func parseRecord(url: String, parserData: ParserData) async -> HTMLMetadataRecord {
+ HTMLMetadataRecord(url: url, metadata: HTMLMetadataParser.htmlMetadata(with: parserData))
+ }
+
func cacheRecord(_ record: HTMLMetadataRecord) {
cache.withLock { $0[record.url] = record }
}
@@ -119,11 +152,19 @@ nonisolated private extension HTMLMetadataDownloader {
do {
let downloadResponse = try await Downloader.shared.download(actualURL, userAgentStyle: .browser)
+ // A captive portal’s login page would give the home page the portal’s icons.
+ // Only http is checked, since a portal can’t redirect https without a certificate error.
+ if actualURL.scheme?.lowercased() == "http", let responseURL = downloadResponse.response?.url, Self.isRedirectToAnotherHost(from: actualURL, to: responseURL) {
+ await returnStaleCacheIfAvailable(url)
+ let userInfo = [NSLocalizedDescriptionKey: "Redirected to \(responseURL.host() ?? responseURL.absoluteString)"]
+ activityLog.didFail(.htmlMetadataDownloader, kind: kind, error: NSError(domain: "NetNewsWire", code: -1, userInfo: userInfo))
+ return
+ }
+
if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK {
let urlToUse = response.url ?? actualURL
let parserData = ParserData(url: urlToUse.absoluteString, data: data)
- let htmlMetadata = HTMLMetadataParser.htmlMetadata(with: parserData)
- let record = HTMLMetadataRecord(url: url, metadata: htmlMetadata)
+ let record = await Self.parseRecord(url: url, parserData: parserData)
let statusCode = response.forcedStatusCode
await HTMLMetadataDatabase.shared.save(record, statusCode: statusCode)
diff --git a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataRecord.swift b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataRecord.swift
index 364bfdf3b..acc11ae80 100644
--- a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataRecord.swift
+++ b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataRecord.swift
@@ -101,7 +101,7 @@ public extension HTMLMetadataRecord {
public extension HTMLMetadataRecord {
- func bestWebsiteIconURL() -> String? {
+ func bestHomePageIconURL() -> String? {
if let appleTouchIcon = largestAppleTouchIcon() {
return appleTouchIcon
}
diff --git a/Modules/Images/Package.swift b/Modules/Images/Package.swift
index f65971be9..95abc0c9e 100644
--- a/Modules/Images/Package.swift
+++ b/Modules/Images/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
let package = Package(
name: "Images",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(
name: "Images",
@@ -13,6 +13,7 @@ let package = Package(
dependencies: [
.package(path: "../RSCore"),
.package(path: "../RSDatabase"),
+ .package(path: "../RSParser"),
.package(path: "../RSWeb"),
.package(path: "../Account"),
.package(path: "../Articles"),
@@ -25,6 +26,7 @@ let package = Package(
dependencies: [
"RSCore",
"RSDatabase",
+ "RSParser",
"RSWeb",
"Account",
"Articles",
@@ -36,6 +38,14 @@ let package = Package(
.enableUpcomingFeature("InferIsolatedConformances"),
.unsafeFlags(["-warnings-as-errors"])
]
+ ),
+ .testTarget(
+ name: "ImagesTests",
+ dependencies: ["Images"],
+ swiftSettings: [
+ .enableUpcomingFeature("NonisolatedNonsendingByDefault"),
+ .enableUpcomingFeature("InferIsolatedConformances")
+ ]
)
]
)
diff --git a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift
new file mode 100644
index 000000000..f918ed6c7
--- /dev/null
+++ b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift
@@ -0,0 +1,274 @@
+//
+// ArticleThumbnailFinder.swift
+// Images
+//
+// Created by Brent Simmons on 10/25/26.
+//
+
+import Foundation
+import Articles
+import RSCore
+import RSParser
+import RSWeb
+import ActivityLog
+
+extension Notification.Name {
+ /// Posted when a thumbnail image fails to download or is rejected for its size.
+ /// `thumbnailURL(for:mode:)` now skips that URL, so articles that used it may have a different thumbnail.
+ /// userInfo key: `ArticleThumbnailFinder.articleIDsKey` (`Set`, the articles whose `thumbnailURL(for:mode:)` was that URL).
+ public static let articleThumbnailDownloadDidFail = Notification.Name("ArticleThumbnailDownloadDidFail")
+}
+
+/// Finds the image that stands for an article in the timeline.
+///
+/// Sources: the provided thumbnail, the article’s image, the first significant image
+/// attachment, and the first few significant images in the article’s HTML. Small mode
+/// tries them in that order. Large mode tries the provided thumbnail last, since it’s usually
+/// too small to fill the timeline’s width. Blogger’s, for instance, are 72-pixel square crops.
+///
+/// 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 memory is low, or, on iOS, until the app goes to the background.
+/// The Mac keeps them on switching apps, since large-mode row heights ask for every row.
+/// 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.
+///
+/// URLs that recently failed to download, and images too small, too narrow, or unreadable
+/// to be thumbnails, are skipped, so they fall through to the next source.
+///
+/// `ThumbnailDownloader` downloads and decodes the images.
+@MainActor public final class ArticleThumbnailFinder {
+
+ public static let shared = ArticleThumbnailFinder(imageDatabase: .shared)
+
+ public static let articleIDsKey = "articleIDs"
+
+ private let imageDatabase: ImageDatabase
+ private var htmlThumbnailURLs = [String: [String]]() // articleID: thumbnailURLs, in document order. Empty when the HTML has none.
+ private var urlsThatFailedToDecode = Set() // So a failure notification can’t lead to the same attempt again
+ private var chosenThumbnailURLs = [ThumbnailMode: [String: ChosenThumbnailURL]]() // articleID: the URL thumbnailURL(for:mode:) chose, since large-mode row heights ask for every row
+
+ /// HTML images kept per article, so one that fails or is too small falls through to the next.
+ nonisolated private static let maxHTMLThumbnailURLsPerArticle = 3
+ /// Entries per mode in chosenThumbnailURLs. Past this, that mode’s entries are emptied.
+ private static let maxChosenThumbnailURLCount = 50_000
+
+ init(imageDatabase: ImageDatabase) {
+ self.imageDatabase = imageDatabase
+
+ NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
+ #if os(iOS)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
+ #endif
+ NotificationCenter.default.addObserver(self, selector: #selector(handleNetworkStatusDidChange(_:)), name: .networkStatusDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleThumbnailDownloadDidFail(_:)), name: .thumbnailDownloadDidFail, object: nil)
+ }
+
+ /// 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: ThumbnailMode) -> 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) ?? cachedOrParsedHTMLThumbnailURLs(for: article).first { !hasFailed($0) } ?? usableProvidedURL(Self.normalizedURLString(article.rawThumbnailLink))
+ if chosenThumbnailURLs[mode, default: [:]].count >= Self.maxChosenThumbnailURLCount {
+ chosenThumbnailURLs[mode] = nil
+ }
+ chosenThumbnailURLs[mode, default: [:]][articleID] = ChosenThumbnailURL(article, thumbnailURL: thumbnailURL)
+ return thumbnailURL
+ }
+
+ /// Parses, off the main thread, the HTML of articles that have no usable provided image and no cached result.
+ public func findThumbnailURLs(for articles: some Collection) 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) {
+ if error.decodingFailed || error.rejectedPixelSize != nil {
+ urlsThatFailedToDecode.insert(url)
+ }
+ // A transient decoding failure counts, since the row would otherwise keep waiting for an image that isn’t coming.
+ if !error.isTransient || error.decodingFailed {
+ thumbnailURLDidFail(url)
+ }
+ }
+
+ /// Forgets the chosen thumbnail URL of each article that used `url`, and posts `.articleThumbnailDownloadDidFail`.
+ func thumbnailURLDidFail(_ url: String) {
+ var articleIDs = Set()
+ for chosenThumbnailURLsForMode in chosenThumbnailURLs.values {
+ articleIDs.formUnion(chosenThumbnailURLsForMode.filter { $0.value.thumbnailURL == url }.keys)
+ }
+ guard !articleIDs.isEmpty else {
+ return
+ }
+ forgetChosenThumbnailURLs(articleIDs)
+ NotificationCenter.default.post(name: .articleThumbnailDownloadDidFail, object: self, userInfo: [Self.articleIDsKey: articleIDs])
+ }
+
+ // MARK: - Notifications
+
+ @objc func handleLowMemory(_ notification: Notification) {
+ emptyHTMLThumbnailCache()
+ }
+
+ #if os(iOS)
+ @objc func handleAppDidGoToBackground(_ notification: Notification) {
+ emptyHTMLThumbnailCache()
+ }
+ #endif
+
+ /// What failed to decode may have been a captive portal’s login page, not the image.
+ @objc func handleNetworkStatusDidChange(_ notification: Notification) {
+ urlsThatFailedToDecode.removeAll()
+ chosenThumbnailURLs.removeAll()
+ }
+
+ @objc func handleThumbnailDownloadDidFail(_ notification: Notification) {
+ guard let url = notification.userInfo?[ThumbnailDownloader.urlKey] as? String, let error = notification.userInfo?[ThumbnailDownloader.errorKey] as? ImageDownloadError else {
+ return
+ }
+ thumbnailDidFail(url: url, error: error)
+ }
+}
+
+// MARK: - Private
+
+private extension ArticleThumbnailFinder {
+
+ /// Keeps the article’s image fields, not the article, which would keep its HTML in memory.
+ struct ChosenThumbnailURL {
+ let rawThumbnailLink: String?
+ let rawImageLink: String?
+ let attachments: [Attachment]?
+ let thumbnailURL: String?
+
+ init(_ article: Article, thumbnailURL: String?) {
+ self.rawThumbnailLink = article.rawThumbnailLink
+ self.rawImageLink = article.rawImageLink
+ self.attachments = article.attachments
+ self.thumbnailURL = thumbnailURL
+ }
+
+ /// Articles are immutable, so a different instance with the same articleID may have different images.
+ func hasSameImages(as article: Article) -> Bool {
+ rawThumbnailLink == article.rawThumbnailLink && rawImageLink == article.rawImageLink && attachments == article.attachments
+ }
+ }
+
+ struct ArticleHTML: Sendable {
+ let articleID: String
+ let html: String
+ let baseURL: URL?
+
+ @MainActor init?(_ article: Article) {
+ guard let html = article.contentHTML ?? article.summary, !html.isEmpty else {
+ return nil
+ }
+ self.articleID = article.articleID
+ 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)
+ }
+ }
+
+ func forgetChosenThumbnailURLs(_ articleIDs: some Sequence) {
+ for mode in ThumbnailMode.allCases {
+ for articleID in articleIDs {
+ chosenThumbnailURLs[mode]?[articleID] = nil
+ }
+ }
+ }
+
+ /// The provided image to use ahead of images in the HTML.
+ func providedThumbnailURL(for article: Article, mode: ThumbnailMode) -> String? {
+ switch mode {
+ case .small:
+ usableProvidedURL(Self.normalizedURLString(article.rawThumbnailLink)) ?? usableProvidedURL(Self.normalizedURLString(article.rawImageLink)) ?? usableProvidedURL(Self.firstSignificantImageAttachmentURL(article))
+ case .large:
+ usableProvidedURL(Self.normalizedURLString(article.rawImageLink)) ?? usableProvidedURL(Self.firstSignificantImageAttachmentURL(article))
+ }
+ }
+
+ func usableProvidedURL(_ urlString: String?) -> String? {
+ guard let urlString, !hasFailed(urlString), SignificantImageFilter.isSignificant(urlString: urlString, width: nil, height: nil) else {
+ return nil
+ }
+ return urlString
+ }
+
+ /// True when the URL recently failed to download, or its image was too small, too narrow, or unreadable.
+ func hasFailed(_ urlString: String) -> Bool {
+ imageDatabase.recentlyFailed(url: urlString) || imageDatabase.isUnsuitableForThumbnail(url: urlString) || urlsThatFailedToDecode.contains(urlString)
+ }
+
+ func needsHTMLParsing(_ article: Article) -> Bool {
+ guard htmlThumbnailURLs[article.articleID] == nil else {
+ return false
+ }
+ // Large mode uses the HTML for any article that small mode does, and for those with only a provided thumbnail.
+ return providedThumbnailURL(for: article, mode: .large) == nil
+ }
+
+ 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
+ }
+
+ /// 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? {
+ guard let attachments = article.attachments else {
+ return nil
+ }
+ for attachment in attachments where attachment.displayMedium == .image {
+ if SignificantImageFilter.isSignificant(urlString: attachment.url, width: attachment.width, height: attachment.height) {
+ return attachment.url
+ }
+ }
+ return nil
+ }
+
+ /// Encodes spaces, as `Article.imageLink` does.
+ static func normalizedURLString(_ link: String?) -> String? {
+ guard let link, !link.isEmpty else {
+ return nil
+ }
+ return URL.encodeSpacesIfNeeded(link)?.absoluteString ?? link
+ }
+}
diff --git a/Modules/Images/Sources/Images/AuthorAvatarDownloader.swift b/Modules/Images/Sources/Images/AuthorAvatarDownloader.swift
index a3badc980..0cc9062f4 100644
--- a/Modules/Images/Sources/Images/AuthorAvatarDownloader.swift
+++ b/Modules/Images/Sources/Images/AuthorAvatarDownloader.swift
@@ -12,96 +12,32 @@ import RSCore
import ActivityLog
extension Notification.Name {
- public static let AvatarDidBecomeAvailable = Notification.Name("AvatarDidBecomeAvailableNotification") // userInfo key: "url" (the avatarURL)
+ /// userInfo key: `AuthorAvatarDownloader.avatarURLKey`.
+ public static let avatarDidChange = Notification.Name("AvatarDidChange")
}
@MainActor public final class AuthorAvatarDownloader {
public static let shared = AuthorAvatarDownloader()
+ public static let avatarURLKey = "avatarURL"
- private let imageDownloader = ImageDownloader.shared
- private var cache = [String: IconImage]() // avatarURL: RSImage
- private var waitingForAvatarURLs = Set()
+ private var avatarURLs = Set() // Every avatar URL looked up, so a changed image is posted too
- init() {
- NotificationCenter.default.addObserver(self, selector: #selector(imageDidBecomeAvailable(_:)), name: .imageDidBecomeAvailable, object: imageDownloader)
- NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
+ private init() {
+ NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDidBecomeAvailable(_:)), name: .iconImageDidBecomeAvailable, object: IconImageDownloader.shared)
}
- @objc func handleLowMemory(_ notification: Notification) {
- cache.removeAll()
- }
-
- @objc func handleAppDidGoToBackground(_ notification: Notification) {
- cache.removeAll()
- }
-
- public func image(for author: Author) -> IconImage? {
-
+ public func avatar(for author: Author) -> IconLookup {
guard let avatarURL = author.avatarURL else {
- return nil
+ return .unavailable
}
-
- if let cachedImage = cache[avatarURL] {
- return cachedImage
- }
-
- let kind = ActivityKind.downloadAvatar(avatarURL: avatarURL)
- if let imageData = imageDownloader.image(for: avatarURL, activityOwner: .avatarDownloader, activityKind: kind, activityDetail: author.name) {
- scaleAndCacheImageData(imageData, avatarURL)
- } else {
- waitingForAvatarURLs.insert(avatarURL)
- }
-
- return nil
+ avatarURLs.insert(avatarURL)
+ return IconImageDownloader.shared.iconImage(for: avatarURL, activityOwner: .avatarDownloader, activityKind: .downloadAvatar(avatarURL: avatarURL), activityDetail: author.name)
}
- public func cachedImage(for author: Author) -> IconImage? {
- guard let avatarURL = author.avatarURL else {
- return nil
- }
- return cache[avatarURL]
- }
-
- @objc func imageDidBecomeAvailable(_ note: Notification) {
- guard let avatarURL = note.userInfo?["url"] as? String else {
+ @objc func handleIconImageDidBecomeAvailable(_ notification: Notification) {
+ guard let avatarURL = notification.userInfo?[IconImageDownloader.urlKey] as? String, avatarURLs.contains(avatarURL) else {
return
}
- guard waitingForAvatarURLs.contains(avatarURL) else {
- return
- }
- guard let imageData = imageDownloader.image(for: avatarURL) else {
- return
- }
- scaleAndCacheImageData(imageData, avatarURL)
- }
-}
-
-@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)
- }
- }
- }
- }
-
- func handleImageDidBecomeAvailable(_ avatarURL: String, _ image: RSImage) {
- if cache[avatarURL] == nil {
- cache[avatarURL] = IconImage(image)
- }
- if waitingForAvatarURLs.contains(avatarURL) {
- waitingForAvatarURLs.remove(avatarURL)
- postAvatarDidBecomeAvailableNotification(avatarURL)
- }
- }
-
- func postAvatarDidBecomeAvailableNotification(_ avatarURL: String) {
- DispatchQueue.main.async {
- NotificationCenter.default.post(name: .AvatarDidBecomeAvailable, object: self, userInfo: ["url": avatarURL])
- }
+ NotificationCenter.default.post(name: .avatarDidChange, object: self, userInfo: [Self.avatarURLKey: avatarURL])
}
}
diff --git a/Modules/Images/Sources/Images/DownloadFailureTable.swift b/Modules/Images/Sources/Images/DownloadFailureTable.swift
index a3c168e43..857996c33 100644
--- a/Modules/Images/Sources/Images/DownloadFailureTable.swift
+++ b/Modules/Images/Sources/Images/DownloadFailureTable.swift
@@ -17,7 +17,6 @@ struct DownloadFailureTable {
private struct Column {
static let url = "url"
static let lastChecked = "lastChecked"
- static let statusCode = "statusCode"
}
/// Returns all failures as `url : lastFailureDate`.
@@ -39,11 +38,10 @@ struct DownloadFailureTable {
return results
}
- static func save(url: String, statusCode: Int?, database: FMDatabase) {
+ static func save(url: String, database: FMDatabase) {
let dictionary: DatabaseDictionary = [
Column.url: url,
- Column.lastChecked: Date().timeIntervalSince1970,
- Column.statusCode: statusCode as Any
+ Column.lastChecked: Date().timeIntervalSince1970
]
database.insertRow(dictionary, insertType: .orReplace, tableName: name)
}
diff --git a/Modules/Images/Sources/Images/DownloadedImageCache.swift b/Modules/Images/Sources/Images/DownloadedImageCache.swift
new file mode 100644
index 000000000..d2ba975f8
--- /dev/null
+++ b/Modules/Images/Sources/Images/DownloadedImageCache.swift
@@ -0,0 +1,618 @@
+//
+// DownloadedImageCache.swift
+// Images
+//
+// Created by Brent Simmons on 10/26/26.
+//
+
+import Foundation
+import os
+import RSCore
+import RSWeb
+import ActivityLog
+
+extension Notification.Name {
+ /// Posted when a check with the server replaces the stored copy of an image with a changed one.
+ /// userInfo key: `DownloadedImageCache.urlKey`.
+ static let downloadedImageDidChange = Notification.Name("DownloadedImageDidChange")
+}
+
+/// Downloads each image URL once and keeps one copy on disk, shared by icons and thumbnails.
+///
+/// The copy is the image as downloaded, since the article view shows it at full size.
+/// `IconImageDownloader` and `ThumbnailDownloader` make their own sizes from it.
+/// Requests for a URL that’s already being read or downloaded share that work.
+///
+/// A copy made from an image, such as a scaled icon, can be stored next to it with a suffix.
+/// It’s kept while the image is, and removed with it. It doesn’t count toward the limit.
+/// Once an icon’s scaled copy is saved, its original is deleted, since only the scaled copy is shown.
+///
+/// At launch, the least recently used copies are deleted from disk until the rest total no more than
+/// `maximumStoredByteCount`. The total can go over that until the next launch.
+/// Icons don’t count toward the limit and aren’t removed for it, so thumbnails can’t push them out.
+/// Instead, icons not used in `unusedIconExpirationInterval` are deleted at launch.
+///
+/// Icons can change at the same URL, so callers that show icons pass `checksForUpdates`.
+/// An icon used after its `nextCheck` date is still used, and the server is asked in the
+/// background whether it changed. Unchanged icons cost a 304 response, not the image again.
+/// Other images, such as thumbnails, keep the version first downloaded.
+///
+/// After a transient failure, such as a timeout, a 5xx response, or a response that isn’t an image,
+/// the URL isn’t requested again until a retry date. After a 429, a 503, or no response, nothing else
+/// on its host is requested either. The wait is `retryWait`, or the server’s Retry-After when that’s longer.
+@MainActor final class DownloadedImageCache {
+
+ static let shared = DownloadedImageCache()
+ static let urlKey = "url"
+ /// Scaled icons are saved next to their originals, so they aren’t rescaled after a memory cache is emptied.
+ private static let scaledIconSuffix = String(RSImage.maxIconPixelSize)
+
+ private static let folderName = "DownloadedImages"
+ private static let svgMIMEType = "image/svg+xml"
+ private static let maximumConcurrentLimitedDownloads = 4
+ /// Requests to one HTTP/1.1 host run one at a time, so a stalled host could otherwise hold every slot.
+ private static let maximumDownloadsPerHost = 2
+ /// A few screens of thumbnails.
+ private static let maximumWaitingLimitedDownloads = 60
+ /// Larger images aren’t saved for the timeline. The article view and icons have no limit.
+ private static let maximumLimitedDownloadByteCount = 25 * 1024 * 1024
+
+ #if os(macOS)
+ private static let maximumStoredByteCount = 300 * 1024 * 1024
+ #else
+ private static let maximumStoredByteCount = 150 * 1024 * 1024
+ #endif
+ private static let readNoteInterval = TimeInterval(days: 1)
+ /// Past this, `readDatesNoted` is emptied, so a session lasting weeks doesn’t keep every URL it used.
+ private static let maximumReadDatesNotedCount = 10_000
+ /// Eight days, not seven, so checks spread across the days of the week.
+ nonisolated private static let defaultCheckInterval = TimeInterval(days: 8)
+ /// A server’s max-age is kept within these, so a misconfigured server isn’t asked too often.
+ nonisolated private static let minimumCheckInterval = TimeInterval(days: 3)
+ nonisolated private static let maximumCheckInterval = TimeInterval(days: 30)
+ /// Check intervals vary by up to this fraction either way, so images downloaded together aren’t all checked together.
+ nonisolated private static let checkIntervalJitter = 0.2
+ /// A file and its record are saved moments apart, so anything this recent may be mid-save.
+ nonisolated private static let recentChangeInterval: TimeInterval = 60
+ nonisolated private static let unusedIconExpirationInterval = TimeInterval(days: 180)
+ /// Disk keys are hex, so this can’t appear in an image’s own key.
+ nonisolated private static let derivedKeySeparator: Character = "-"
+ nonisolated private static let retryWait: TimeInterval = 37 * 60
+
+ nonisolated private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "DownloadedImageCache")
+
+ private let diskCache: BinaryDiskCache
+ private let downloadQueue = ThumbnailTaskQueue(maximumRunningCount: maximumConcurrentLimitedDownloads, maximumWaitingCount: maximumWaitingLimitedDownloads, maximumRunningCountPerGroup: maximumDownloadsPerHost)
+ private var tasks = [String: Task, Never>]() // url: task
+ private var readDatesNoted = [String: Date]() // url: date
+ private var iconURLsNoted = Set()
+ private var retryDates = [String: Date]() // url: end of the wait after its last transient failure
+ private var hostRetryDates = [String: Date]() // lowercased host: end of the wait after its last transient failure
+
+ private init() {
+ let folder = AppConfig.cacheSubfolder(named: Self.folderName)
+ self.diskCache = BinaryDiskCache(folder: folder.path)
+
+ NotificationCenter.default.addObserver(self, selector: #selector(handleNetworkStatusDidChange(_:)), name: .networkStatusDidChange, object: nil)
+
+ Task {
+ await self.removeImagesOverSizeLimit()
+ }
+ }
+
+ /// False when offline or in Low Data Mode.
+ static var networkAllowsDownloads: Bool {
+ NetworkMonitor.shared.isConnected && !NetworkMonitor.shared.isConstrained
+ }
+
+ /// The stored copy, read from disk or downloaded. With `usesDownloadQueue`, a download
+ /// waits its turn in the download queue, and doesn’t start when offline or in Low Data Mode.
+ /// Without it, a download starts right away, as does a waiting download for the same URL.
+ /// Activity log fires only when the request reaches the network.
+ func imageData(for url: String, usesDownloadQueue: Bool, checksForUpdates: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async throws(ImageDownloadError) -> Data {
+ if let task = tasks[url] {
+ if usesDownloadQueue {
+ prioritizeDownload(for: url)
+ } else {
+ downloadQueue.startNow(key: url)
+ }
+ return try await task.value.get()
+ }
+
+ let task = Task {
+ await findImage(url, usesDownloadQueue: usesDownloadQueue, checksForUpdates: checksForUpdates, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail)
+ }
+ tasks[url] = task
+ let result = await task.value
+ tasks[url] = nil
+ return try result.get()
+ }
+
+ /// Moves a waiting download to the front, for an image whose row is shown again.
+ func prioritizeDownload(for url: String) {
+ downloadQueue.prioritize(key: url)
+ }
+
+ /// True when the URL or its host had a transient failure, and its wait hasn’t ended.
+ func isWaitingToRetry(_ url: String) -> Bool {
+ let now = Date()
+ if let retryDate = retryDates[url], retryDate > now {
+ return true
+ }
+ if let host = Self.host(url), let retryDate = hostRetryDates[host], retryDate > now {
+ return true
+ }
+ return false
+ }
+
+ /// Nil when none has been saved.
+ func scaledIconData(for url: String) async -> Data? {
+ await Self.readFromDisk(diskCache, key: Self.derivedDiskKey(url, suffix: Self.scaledIconSuffix))
+ }
+
+ /// Deletes the original, which an og:image, for instance, can make large. Kept if the scaled copy can’t be written.
+ func saveScaledIconData(_ data: Data, for url: String) async {
+ do {
+ try await Self.saveToDisk(diskCache, key: Self.derivedDiskKey(url, suffix: Self.scaledIconSuffix), data: data)
+ } catch {
+ Self.logger.error("Couldn’t write scaled icon for \(url): \(error.localizedDescription)")
+ return
+ }
+ await Self.deleteFromDisk(diskCache, keys: [Self.diskKey(url)])
+ }
+
+ /// At most once a day per image: saves the access date, which orders images for removal,
+ /// and, when `checksForUpdates`, checks with the server if the copy is due.
+ /// Callers that keep images in memory call this on memory hits too, so images in use aren’t removed first.
+ ///
+ /// `checksForUpdates` means the image is an icon, which is saved once per session, so an image first saved as a thumbnail is kept as an icon.
+ func imageWasUsed(_ url: String, checksForUpdates: Bool) {
+ if checksForUpdates && !iconURLsNoted.contains(url) {
+ iconURLsNoted.insert(url)
+ ImageDatabase.shared.saveDownloadedImageIsIcon(url: url)
+ }
+
+ let now = Date()
+ if let readDate = readDatesNoted[url], now.timeIntervalSince(readDate) < Self.readNoteInterval {
+ return
+ }
+ if readDatesNoted.count >= Self.maximumReadDatesNotedCount {
+ readDatesNoted.removeAll()
+ }
+ readDatesNoted[url] = now
+ ImageDatabase.shared.saveDownloadedImageAccessDate(url: url)
+ guard checksForUpdates else {
+ return
+ }
+ Task {
+ await revalidateIfDue(url)
+ }
+ }
+
+ /// Failures while offline say nothing about the servers, so retries can start right away,
+ /// except where a server asked for a wait with Retry-After.
+ /// What wasn’t an image may have been a captive portal’s login page.
+ @objc func handleNetworkStatusDidChange(_ notification: Notification) {
+ // Only Retry-After makes a wait longer than retryWait.
+ let latestRetryDateWithoutRetryAfter = Date().addingTimeInterval(Self.retryWait)
+ retryDates = retryDates.filter { $0.value > latestRetryDateWithoutRetryAfter }
+ hostRetryDates = hostRetryDates.filter { $0.value > latestRetryDateWithoutRetryAfter }
+ }
+}
+
+private extension DownloadedImageCache {
+
+ func findImage(_ url: String, usesDownloadQueue: Bool, checksForUpdates: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async -> Result {
+ if let data = await Self.readFromDisk(diskCache, key: Self.diskKey(url)) {
+ imageWasUsed(url, checksForUpdates: checksForUpdates)
+ return .success(data)
+ }
+
+ if isWaitingToRetry(url) {
+ return .failure(.notAttempted)
+ }
+ let host = Self.host(url)
+ if usesDownloadQueue {
+ guard Self.networkAllowsDownloads else {
+ return .failure(.notAttempted)
+ }
+ switch await downloadQueue.waitForTurn(key: url, group: host) {
+ case .dropped:
+ return .failure(.notAttempted)
+ case .start:
+ // The network or a retry wait may have changed while this was queued.
+ guard !isWaitingToRetry(url), Self.networkAllowsDownloads else {
+ downloadQueue.taskDidFinish(group: host)
+ return .failure(.notAttempted)
+ }
+ case .startNow:
+ break
+ }
+ }
+ let maximumByteCount = usesDownloadQueue ? Self.maximumLimitedDownloadByteCount : nil
+ let result = await downloadImageFromNetwork(url, maximumByteCount: maximumByteCount, isIcon: checksForUpdates, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail)
+ if usesDownloadQueue {
+ downloadQueue.taskDidFinish(group: host)
+ }
+ noteDownloadResult(result, url: url)
+ return result
+ }
+
+ /// Any response that isn’t a transient failure means the host is answering, so its wait ends.
+ func noteDownloadResult(_ result: Result, url: String) {
+ let host = Self.host(url)
+ guard case .failure(let error) = result, error.isTransient else {
+ retryDates[url] = nil
+ if let host {
+ hostRetryDates[host] = nil
+ }
+ return
+ }
+ let now = Date()
+ retryDates[url] = Self.retryDate(after: retryDates[url], retryAfter: error.retryAfter, now: now)
+ if let host, Self.failureAppliesToHost(statusCode: error.statusCode) {
+ hostRetryDates[host] = Self.retryDate(after: hostRetryDates[host], retryAfter: error.retryAfter, now: now)
+ }
+ }
+
+ /// A host that’s rate limiting, overloaded, or not answering gets a wait. Other failures may be just the one URL.
+ static func failureAppliesToHost(statusCode: Int?) -> Bool {
+ guard let statusCode else {
+ return true
+ }
+ return statusCode == HTTPResponseCode.tooManyRequests || statusCode == HTTPResponseCode.serviceUnavailable
+ }
+
+ static func host(_ url: String) -> String? {
+ URL(string: url)?.host()?.lowercased(with: localeForLowercasing)
+ }
+
+ func downloadImageFromNetwork(_ url: String, maximumByteCount: Int?, isIcon: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async -> Result {
+ let activityLog = ActivityLog.shared
+ // Thumbnails log only failures, since a few screens of scrolling would otherwise push out the rest of the log.
+ let logsOnlyFailure = activityOwner == .thumbnailDownloader
+ if !logsOnlyFailure, let activityOwner, let activityKind {
+ activityLog.createActivity(owner: activityOwner, kind: activityKind, detail: activityDetail)
+ activityLog.didStart(activityOwner, kind: activityKind)
+ }
+
+ do {
+ let (data, downloadResponse) = try await downloadImage(url, maximumByteCount: maximumByteCount, isIcon: isIcon)
+ if !logsOnlyFailure, let activityOwner, let activityKind {
+ let message = downloadResponse.data.map(ActivityLog.dataSizeMessage)
+ activityLog.didComplete(activityOwner, kind: activityKind, message: message, returnedFromCache: downloadResponse.returnedFromCache)
+ }
+ ImageDatabase.shared.clearFailure(url: url)
+ return .success(data)
+ } catch {
+ if let activityOwner, let activityKind {
+ if logsOnlyFailure {
+ activityLog.createActivity(owner: activityOwner, kind: activityKind, detail: activityDetail)
+ }
+ activityLog.didFail(activityOwner, kind: activityKind, error: error)
+ }
+ if error.rejectedByteCount != nil {
+ // Too large only for the timeline, so icons and the article view can still use it.
+ ImageDatabase.shared.saveUnsuitableForThumbnail(url: url)
+ } else if !error.isTransient {
+ ImageDatabase.shared.recordFailure(url: url)
+ }
+ return .failure(error)
+ }
+ }
+
+ func downloadImage(_ url: String, maximumByteCount: Int?, isIcon: Bool) async throws(ImageDownloadError) -> (Data, DownloadResponse) {
+ guard let imageURL = URL(string: url) else {
+ throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: false)
+ }
+
+ let downloadResponse: DownloadResponse
+ do {
+ // Not cached by Downloader, since the copy on disk is the cache.
+ downloadResponse = try await Downloader.shared.download(imageURL, userAgentStyle: .browser, cachesResponse: false)
+ } catch {
+ Self.logger.error("Error downloading image at \(url) \(error.localizedDescription)")
+ // DNS and certificate errors stay transient, since a captive portal causes them too.
+ let isUnsupportedURL = (error as? URLError)?.code == .unsupportedURL
+ throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: !isUnsupportedURL)
+ }
+
+ let httpResponse = downloadResponse.response as? HTTPURLResponse
+ let statusCode = httpResponse?.statusCode
+ if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK {
+ if let maximumByteCount, data.count > maximumByteCount {
+ throw ImageDownloadError(statusCode: statusCode, decodingFailed: false, isTransient: false, rejectedByteCount: data.count)
+ }
+ // Transient, since a captive portal’s login page would otherwise fail every image for days.
+ guard try await saveImage(data, url: url, httpResponse: httpResponse, isIcon: isIcon) else {
+ throw ImageDownloadError(statusCode: statusCode, decodingFailed: true, isTransient: true)
+ }
+ return (data, downloadResponse)
+ }
+
+ // A 2xx response with no body.
+ if let response = downloadResponse.response, response.statusIsOK {
+ throw ImageDownloadError(statusCode: statusCode, decodingFailed: true, isTransient: false)
+ }
+ var isTransient = true
+ if let statusCode {
+ isTransient = Self.isTransient(statusCode: statusCode)
+ }
+ throw ImageDownloadError(statusCode: statusCode, decodingFailed: false, isTransient: isTransient, retryAfter: Self.retryAfter(httpResponse))
+ }
+
+ static func retryAfter(_ httpResponse: HTTPURLResponse?) -> TimeInterval? {
+ guard let retryAfterValue = httpResponse?.value(forHTTPHeaderField: HTTPResponseHeader.retryAfter) else {
+ return nil
+ }
+ return TimeInterval(retryAfterValue.trimmingCharacters(in: .whitespaces))
+ }
+
+ /// Returns false, and saves nothing, when the data isn’t an image, such as an HTML error page.
+ /// SVG is saved, though ImageIO can’t read it.
+ /// Throws a transient error, and records nothing, when the file can’t be written.
+ func saveImage(_ data: Data, url: String, httpResponse: HTTPURLResponse?, isIcon: Bool) async throws(ImageDownloadError) -> Bool {
+ let pixelSize = await Self.pixelSize(data)
+ guard pixelSize != nil || httpResponse?.mimeType == Self.svgMIMEType else {
+ Self.logger.info("Didn’t save unreadable image at \(url)")
+ return false
+ }
+ do {
+ try await Self.saveToDisk(diskCache, key: Self.diskKey(url), data: data)
+ } catch {
+ Self.logger.error("Couldn’t write image from \(url): \(error.localizedDescription)")
+ throw ImageDownloadError(statusCode: httpResponse?.statusCode, decodingFailed: false, isTransient: true)
+ }
+ var conditionalGetInfo: HTTPConditionalGetInfo?
+ if let httpResponse {
+ conditionalGetInfo = HTTPConditionalGetInfo(urlResponse: httpResponse)
+ }
+ let nextCheck = Self.nextCheck(httpResponse, hasValidators: conditionalGetInfo != nil)
+ // An icon downloaded again as a thumbnail, since only its scaled copy was kept, stays an icon.
+ let isUsedAsIcon = isIcon || iconURLsNoted.contains(url)
+ ImageDatabase.shared.saveDownloadedImage(DownloadedImageRecord(url: url, pixelSize: pixelSize, conditionalGetInfo: conditionalGetInfo, nextCheck: nextCheck, isIcon: isUsedAsIcon))
+ return true
+ }
+
+ // MARK: - Revalidating Images
+
+ /// Doesn’t use the download queue, since icons aren’t limited either.
+ /// A network that doesn’t allow downloads, a retry wait, or a network error leaves `nextCheck` as is, so the next day’s use tries again.
+ func revalidateIfDue(_ url: String) async {
+ guard Self.networkAllowsDownloads, !isWaitingToRetry(url) else {
+ return
+ }
+ // Not <=, which is back-deployed and crashes on iOS 27.2 betas.
+ guard let validation = await ImageDatabase.shared.fetchDownloadedImageValidation(url: url), validation.nextCheck < Date() else {
+ return
+ }
+ guard let imageURL = URL(string: url) else {
+ return
+ }
+
+ var urlRequest = URLRequest(url: imageURL)
+ validation.conditionalGetInfo?.addRequestHeadersToURLRequest(&urlRequest)
+ let downloadResponse: DownloadResponse
+ do {
+ downloadResponse = try await Downloader.shared.download(urlRequest, userAgentStyle: .browser, cachesResponse: false)
+ } catch {
+ return
+ }
+
+ let httpResponse = downloadResponse.response as? HTTPURLResponse
+ var isUnchanged = httpResponse?.statusCode == HTTPResponseCode.notModified
+ if let data = downloadResponse.data, !data.isEmpty, let httpResponse, httpResponse.statusIsOK {
+ // A server without validators sends the whole image even when it hasn’t changed.
+ isUnchanged = await isStoredImage(data, url: url)
+ if !isUnchanged, (try? await saveImage(data, url: url, httpResponse: httpResponse, isIcon: true)) == true {
+ Self.logger.info("Replaced changed image at \(url)")
+ await Self.deleteFromDisk(diskCache, keys: [Self.derivedDiskKey(url, suffix: Self.scaledIconSuffix)])
+ NotificationCenter.default.post(name: .downloadedImageDidChange, object: self, userInfo: [Self.urlKey: url])
+ return
+ }
+ }
+
+ if let httpResponse, Self.isTransient(statusCode: httpResponse.statusCode) {
+ let error = ImageDownloadError(statusCode: httpResponse.statusCode, decodingFailed: false, isTransient: true, retryAfter: Self.retryAfter(httpResponse))
+ noteDownloadResult(.failure(error), url: url)
+ }
+
+ // The server may send a new ETag or Last-Modified with an unchanged image, so later checks can get a 304.
+ var newConditionalGetInfo: HTTPConditionalGetInfo?
+ if isUnchanged, let httpResponse {
+ newConditionalGetInfo = HTTPConditionalGetInfo(urlResponse: httpResponse)
+ }
+
+ // 304 Not Modified, the same bytes, an error response, not an image, or a failed write: keep the copy and check again later.
+ let nextCheck = Self.nextCheck(httpResponse, hasValidators: newConditionalGetInfo != nil || validation.conditionalGetInfo != nil)
+ ImageDatabase.shared.saveDownloadedImageNextCheck(url: url, nextCheck: nextCheck, conditionalGetInfo: newConditionalGetInfo)
+ }
+
+ /// Compares with the original, or, when only the scaled icon is kept, with that. Scaling the same bytes gives the same result.
+ func isStoredImage(_ data: Data, url: String) async -> Bool {
+ if let storedData = await Self.readFromDisk(diskCache, key: Self.diskKey(url)) {
+ return storedData == data
+ }
+ guard let scaledIconData = await scaledIconData(for: url) else {
+ return false
+ }
+ return await Self.scaledIcon(from: data) == scaledIconData
+ }
+
+ // MARK: - Removing Images
+
+ /// Removes the least recently used images, other than icons, until their files total `maximumStoredByteCount`.
+ /// Also removes files with no record and records with no file.
+ func removeImagesOverSizeLimit() async {
+ let startDate = Date()
+
+ guard let records = await ImageDatabase.shared.fetchDownloadedImageUsageByLeastRecentAccess() else {
+ Self.logger.error("Skipped removing images: couldn’t read the image records.")
+ return
+ }
+ guard let files = await Self.storedFiles(diskCache) else {
+ Self.logger.error("Skipped removing images: couldn’t list the images folder.")
+ return
+ }
+ let removal = await Self.imageRemoval(records: records, files: files, urlsInUse: Set(tasks.keys), now: startDate, maximumByteCount: Self.maximumStoredByteCount)
+
+ guard !removal.urls.isEmpty || !removal.keys.isEmpty else {
+ return
+ }
+ ImageDatabase.shared.deleteDownloadedImages(urls: removal.urls)
+ await Self.deleteFromDisk(diskCache, keys: removal.keys)
+ Self.logger.info("Removed \(removal.keys.count) files and \(removal.urls.count) records. \(removal.remainingByteCount) bytes remain.")
+ }
+
+ /// Nil when ImageIO can’t read the image, such as SVG.
+ @concurrent static func pixelSize(_ data: Data) async -> (width: Int, height: Int)? {
+ RSImage.largestFramePixelSize(data)
+ }
+
+ @concurrent static func readFromDisk(_ diskCache: BinaryDiskCache, key: String) async -> Data? {
+ guard let data = diskCache[key], !data.isEmpty else {
+ return nil
+ }
+ return data
+ }
+
+ @concurrent static func saveToDisk(_ diskCache: BinaryDiskCache, key: String, data: Data) async throws {
+ try diskCache.setData(data, forKey: key)
+ }
+
+ @concurrent static func deleteFromDisk(_ diskCache: BinaryDiskCache, keys: Set) async {
+ for key in keys {
+ diskCache[key] = nil
+ }
+ }
+}
+
+// MARK: - Disk Keys, Check Dates, and Removal
+
+extension DownloadedImageCache {
+
+ struct StoredFile: Equatable, Sendable {
+ let modificationDate: Date
+ let byteCount: Int
+ }
+
+ /// Keys are file names. Nil when the folder can’t be listed.
+ @concurrent static func storedFiles(_ diskCache: BinaryDiskCache) async -> [String: StoredFile]? {
+ let folderURL = URL(fileURLWithPath: diskCache.folder)
+ let resourceKeys: Set = [.contentModificationDateKey, .fileSizeKey]
+ guard let fileURLs = try? FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: Array(resourceKeys)) else {
+ return nil
+ }
+ var files = [String: StoredFile]()
+ for fileURL in fileURLs {
+ let resourceValues = try? fileURL.resourceValues(forKeys: resourceKeys)
+ files[fileURL.lastPathComponent] = StoredFile(modificationDate: resourceValues?.contentModificationDate ?? .distantPast, byteCount: resourceValues?.fileSize ?? 0)
+ }
+ return files
+ }
+
+ /// The original data when it’s already small enough or can’t be read.
+ @concurrent static func scaledIcon(from data: Data) async -> Data {
+ RSImage.scaledImageData(data, maxPixelSize: RSImage.maxIconPixelSize) ?? data
+ }
+
+ nonisolated static func diskKey(_ url: String) -> String {
+ url.md5String
+ }
+
+ nonisolated static func derivedDiskKey(_ url: String, suffix: String) -> String {
+ "\(diskKey(url))\(derivedKeySeparator)\(suffix)"
+ }
+
+ /// The key of the image a derived copy was made from, or `key` itself for an image.
+ nonisolated static func baseDiskKey(_ key: String) -> String {
+ guard let separatorIndex = key.firstIndex(of: derivedKeySeparator) else {
+ return key
+ }
+ return String(key[.. Bool {
+ (statusCode >= 500 && statusCode <= 599) || statusCode == HTTPResponseCode.tooManyRequests || statusCode == HTTPResponseCode.requestTimeout
+ }
+
+ /// A failure never shortens a wait already running, such as one from a longer Retry-After.
+ nonisolated static func retryDate(after previousRetryDate: Date?, retryAfter: TimeInterval?, now: Date) -> Date {
+ let retryDate = now.addingTimeInterval(max(retryWait, retryAfter ?? 0))
+ guard let previousRetryDate else {
+ return retryDate
+ }
+ return max(previousRetryDate, retryDate)
+ }
+
+ /// Without an ETag or Last-Modified, a check downloads the whole image, so it waits the longest.
+ nonisolated static func nextCheck(_ httpResponse: HTTPURLResponse?, hasValidators: Bool) -> Date {
+ var interval = defaultCheckInterval
+ if !hasValidators {
+ interval = maximumCheckInterval
+ } else if let httpResponse, let cacheControlInfo = CacheControlInfo(urlResponse: httpResponse) {
+ interval = min(max(cacheControlInfo.maxAge, minimumCheckInterval), maximumCheckInterval)
+ }
+ interval *= Double.random(in: (1 - checkIntervalJitter)...(1 + checkIntervalJitter))
+ return Date().addingTimeInterval(interval)
+ }
+
+ struct ImageRemoval: Equatable {
+ let urls: [String] // Records to delete
+ let keys: Set // Files to delete
+ let remainingByteCount: Int
+ }
+
+ /// `records` are least recently accessed first. Files with no record and records with no file
+ /// are removed, along with derived copies of removed images. Then, when over `maximumByteCount`,
+ /// the least recently accessed images are removed. Icons don’t count toward it and aren’t removed for it.
+ /// Icons not used in `unusedIconExpirationInterval` are removed.
+ /// Nothing changed in the last minute is removed, since it may be in the middle of being saved.
+ /// Images in `urlsInUse` are being read or downloaded, so they’re kept too.
+ @concurrent static func imageRemoval(records: [DownloadedImageUsage], files: [String: StoredFile], urlsInUse: Set, now: Date, maximumByteCount: Int) async -> ImageRemoval {
+ let recentChangeDate = now.addingTimeInterval(-recentChangeInterval)
+
+ var recordsCountedTowardLimit = [(record: DownloadedImageUsage, key: String, byteCount: Int)]()
+ var iconRecords = [(record: DownloadedImageUsage, key: String)]()
+ var recordedKeys = Set()
+ var urls = [String]()
+ // An icon may have only its scaled copy.
+ let keysWithFiles = Set(files.keys.map(baseDiskKey))
+ for record in records {
+ let key = diskKey(record.url)
+ recordedKeys.insert(key)
+ if !keysWithFiles.contains(key) && record.lastAccessed < recentChangeDate {
+ urls.append(record.url)
+ } else if record.isIcon {
+ iconRecords.append((record: record, key: key))
+ } else {
+ recordsCountedTowardLimit.append((record: record, key: key, byteCount: files[key]?.byteCount ?? 0))
+ }
+ }
+ var keys = Set(files.filter { !recordedKeys.contains(baseDiskKey($0.key)) && $0.value.modificationDate < recentChangeDate }.keys)
+ var byteCount = recordsCountedTowardLimit.reduce(0) { $0 + $1.byteCount }
+
+ for (record, key, recordByteCount) in recordsCountedTowardLimit where !urlsInUse.contains(record.url) {
+ // Not >=, which is back-deployed and crashes on iOS 27.2 betas.
+ if byteCount <= maximumByteCount || record.lastAccessed > recentChangeDate {
+ break
+ }
+ urls.append(record.url)
+ keys.insert(key)
+ byteCount -= recordByteCount
+ }
+
+ // Such as icons of deleted feeds.
+ let unusedIconDate = now.addingTimeInterval(-unusedIconExpirationInterval)
+ for (record, key) in iconRecords where record.lastAccessed < unusedIconDate && !urlsInUse.contains(record.url) {
+ urls.append(record.url)
+ keys.insert(key)
+ }
+
+ // Derived copies go with their images.
+ let removedKeys = keys.union(urls.map(diskKey))
+ keys.formUnion(files.keys.filter { baseDiskKey($0) != $0 && removedKeys.contains(baseDiskKey($0)) })
+
+ return ImageRemoval(urls: urls, keys: keys, remainingByteCount: byteCount)
+ }
+}
diff --git a/Modules/Images/Sources/Images/DownloadedImageTable.swift b/Modules/Images/Sources/Images/DownloadedImageTable.swift
new file mode 100644
index 000000000..55290b1b8
--- /dev/null
+++ b/Modules/Images/Sources/Images/DownloadedImageTable.swift
@@ -0,0 +1,152 @@
+//
+// DownloadedImageTable.swift
+// Images
+//
+// Created by Brent Simmons on 10/26/26.
+//
+
+import Foundation
+import RSCore
+import RSWeb
+import RSDatabase
+import RSDatabaseObjC
+
+/// A copy stored by `DownloadedImageCache`. `pixelSize` is nil when ImageIO can’t read the image.
+struct DownloadedImageRecord: Sendable {
+ let url: String
+ let pixelSize: (width: Int, height: Int)?
+ let conditionalGetInfo: HTTPConditionalGetInfo?
+ let nextCheck: Date
+ let isIcon: Bool
+}
+
+/// What `DownloadedImageCache` needs to check with the server whether a copy is current.
+struct DownloadedImageValidation: Sendable {
+ let nextCheck: Date
+ let conditionalGetInfo: HTTPConditionalGetInfo?
+}
+
+/// What `DownloadedImageCache` needs to choose images to remove.
+/// Icons don’t count toward the size limit.
+struct DownloadedImageUsage: Sendable {
+ let url: String
+ let lastAccessed: Date
+ let isIcon: Bool
+}
+
+/// One row per copy stored by `DownloadedImageCache`.
+struct DownloadedImageTable {
+
+ static let name = "downloadedImage"
+
+ private struct Column {
+ static let url = "url"
+ static let pixelWidth = "pixelWidth"
+ static let pixelHeight = "pixelHeight"
+ static let lastAccessed = "lastAccessed"
+ static let etag = "etag"
+ static let lastModified = "lastModified"
+ static let nextCheck = "nextCheck"
+ static let isIcon = "isIcon"
+ }
+
+ /// Keeps each query under the database’s limit on parameters.
+ private static let maximumURLsPerQuery = 500
+
+ /// Every row’s URL and pixel size. `pixelSize` is nil when ImageIO couldn’t read the image.
+ static func fetchPixelSizes(database: FMDatabase) -> [(url: String, pixelSize: (width: Int, height: Int)?)] {
+ var results = [(url: String, pixelSize: (width: Int, height: Int)?)]()
+ guard let resultSet = database.executeQuery("SELECT \(Column.url), \(Column.pixelWidth), \(Column.pixelHeight) FROM \(name);", withArgumentsIn: []) else {
+ return results
+ }
+ defer {
+ resultSet.close()
+ }
+ while resultSet.next() {
+ guard let url = resultSet.string(forColumn: Column.url) else {
+ continue
+ }
+ var pixelSize: (width: Int, height: Int)?
+ if !resultSet.columnIsNull(Column.pixelWidth) && !resultSet.columnIsNull(Column.pixelHeight) {
+ pixelSize = (width: resultSet.long(forColumn: Column.pixelWidth), height: resultSet.long(forColumn: Column.pixelHeight))
+ }
+ results.append((url: url, pixelSize: pixelSize))
+ }
+ return results
+ }
+
+ /// Least recently accessed first. Nil when the query fails.
+ static func fetchUsageByLeastRecentAccess(database: FMDatabase) -> [DownloadedImageUsage]? {
+ var results = [DownloadedImageUsage]()
+ guard let resultSet = database.executeQuery("SELECT \(Column.url), \(Column.lastAccessed), \(Column.isIcon) FROM \(name) ORDER BY \(Column.lastAccessed);", withArgumentsIn: []) else {
+ return nil
+ }
+ defer {
+ resultSet.close()
+ }
+ while resultSet.next() {
+ guard let url = resultSet.string(forColumn: Column.url) else {
+ continue
+ }
+ let lastAccessed = Date(timeIntervalSince1970: resultSet.double(forColumn: Column.lastAccessed))
+ results.append(DownloadedImageUsage(url: url, lastAccessed: lastAccessed, isIcon: resultSet.bool(forColumn: Column.isIcon)))
+ }
+ return results
+ }
+
+ static func fetchValidation(url: String, database: FMDatabase) -> DownloadedImageValidation? {
+ guard let resultSet = database.selectRowsWhere(key: Column.url, equalsAnyValue: [url], tableName: name) else {
+ return nil
+ }
+ defer {
+ resultSet.close()
+ }
+ guard resultSet.next() else {
+ return nil
+ }
+ let nextCheck = Date(timeIntervalSince1970: resultSet.double(forColumn: Column.nextCheck))
+ let conditionalGetInfo = HTTPConditionalGetInfo(lastModified: resultSet.string(forColumn: Column.lastModified), etag: resultSet.string(forColumn: Column.etag))
+ return DownloadedImageValidation(nextCheck: nextCheck, conditionalGetInfo: conditionalGetInfo)
+ }
+
+ static func saveNextCheck(url: String, nextCheck: Date, conditionalGetInfo: HTTPConditionalGetInfo?, database: FMDatabase) {
+ guard let conditionalGetInfo else {
+ database.updateRowsWithValue(nextCheck.timeIntervalSince1970, valueKey: Column.nextCheck, whereKey: Column.url, equals: url, tableName: name)
+ return
+ }
+ let dictionary: DatabaseDictionary = [
+ Column.nextCheck: nextCheck.timeIntervalSince1970,
+ Column.etag: conditionalGetInfo.etag as Any,
+ Column.lastModified: conditionalGetInfo.lastModified as Any
+ ]
+ database.updateRowsWithDictionary(dictionary, whereKey: Column.url, equals: url, tableName: name)
+ }
+
+ static func saveAccessDate(url: String, database: FMDatabase) {
+ database.updateRowsWithValue(Date().timeIntervalSince1970, valueKey: Column.lastAccessed, whereKey: Column.url, equals: url, tableName: name)
+ }
+
+ static func saveIsIcon(url: String, database: FMDatabase) {
+ database.updateRowsWithValue(true, valueKey: Column.isIcon, whereKey: Column.url, equals: url, tableName: name)
+ }
+
+ static func delete(urls: [String], database: FMDatabase) {
+ for urlsChunk in urls.chunked(into: maximumURLsPerQuery) {
+ database.deleteRowsWhere(key: Column.url, equalsAnyValue: urlsChunk, tableName: name)
+ }
+ }
+
+ static func save(_ record: DownloadedImageRecord, database: FMDatabase) {
+ let dictionary: DatabaseDictionary = [
+ Column.url: record.url,
+ Column.pixelWidth: record.pixelSize?.width as Any,
+ Column.pixelHeight: record.pixelSize?.height as Any,
+ Column.lastAccessed: Date().timeIntervalSince1970,
+ Column.etag: record.conditionalGetInfo?.etag as Any,
+ Column.lastModified: record.conditionalGetInfo?.lastModified as Any,
+ Column.nextCheck: record.nextCheck.timeIntervalSince1970,
+ Column.isIcon: record.isIcon
+ ]
+ database.insertRow(dictionary, insertType: .orReplace, tableName: name)
+ }
+}
diff --git a/Modules/Images/Sources/Images/FaviconDownloader.swift b/Modules/Images/Sources/Images/FaviconDownloader.swift
index 3d6075e28..30cc07e4f 100644
--- a/Modules/Images/Sources/Images/FaviconDownloader.swift
+++ b/Modules/Images/Sources/Images/FaviconDownloader.swift
@@ -8,197 +8,147 @@
import Foundation
import os
-import CoreServices
import Articles
import Account
import RSCore
import RSWeb
import HTMLMetadata
+import ActivityLog
import UniformTypeIdentifiers
extension Notification.Name {
-
- public static let FaviconDidBecomeAvailable = Notification.Name("FaviconDidBecomeAvailableNotification") // userInfo key: FaviconDownloader.UserInfoKey.faviconURL
+ /// Posted when a favicon loads. userInfo key: `FaviconDownloader.feedsKey` (`Set`, the feeds that looked it up and use it).
+ public static let faviconDidChange = Notification.Name("FaviconDidChange")
}
+/// Gets a feed’s favicon: the one the feed specifies, or else the first that works of the favicons its home page’s metadata specifies, then `/favicon.ico`.
@MainActor public final class FaviconDownloader {
+
public static let shared = FaviconDownloader()
+ public static let feedsKey = "feeds"
nonisolated static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "FaviconDownloader")
- private let folder: String
- private let diskCache: BinaryDiskCache
- private var singleFaviconDownloaderCache = [String: SingleFaviconDownloader]() // faviconURL: SingleFaviconDownloader
- private var remainingFaviconURLs = [String: ArraySlice]() // homePageURL: array of faviconURLs that haven't been checked yet
- private var currentHomePageHasOnlyFaviconICO = false
+ private var searches = [String: FaviconSearch]() // homePageURL: search through its favicon URLs
+ private var homePagesLookedUp = Set()
+ private var homePagesAwaitingMetadataForSearch = Set()
+ private var homePagesCheckedForNewFavicon = Set()
+ private var homePagesWithTransientSearchFailure = Set()
+ // Feeds that looked up their favicon, so its arrival is posted to them
+ private var feedsByDeclaredFaviconURL = [String: Set]() // favicon URL the feed specifies: feeds
+ private var feedsByHomePageURL = [String: Set]() // home page whose favicon they use: feeds
+ private var faviconURLs = Set() // Every favicon URL looked up
+ private var faviconURLsThatAreNotImages = Set()
- private let queue: DispatchQueue
- private var cache = [Feed: IconImage]() // faviconURL: RSImage
-
- public struct UserInfoKey {
- public static let faviconURL = "faviconURL"
- }
-
- init() {
- let folderURL = AppConfig.cacheSubfolder(named: "Favicons")
- let folder = folderURL.path
- self.folder = folder
- self.diskCache = BinaryDiskCache(folder: folder)
- self.queue = DispatchQueue(label: "FaviconDownloader serial queue - \(folder)")
-
- NotificationCenter.default.addObserver(self, selector: #selector(didLoadFavicon(_:)), name: .DidLoadFavicon, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(htmlMetadataIsAvailable(_:)), name: .htmlMetadataAvailable, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
+ private init() {
+ NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDidBecomeAvailable(_:)), name: .iconImageDidBecomeAvailable, object: IconImageDownloader.shared)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDownloadDidFail(_:)), name: .iconImageDownloadDidFail, object: IconImageDownloader.shared)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleHTMLMetadataAvailable(_:)), name: .htmlMetadataAvailable, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleNetworkStatusDidChange(_:)), name: .networkStatusDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleFeedSettingDidChange(_:)), name: .feedSettingDidChange, object: nil)
}
// MARK: - API
- @objc func handleLowMemory(_ notification: Notification) {
- cache.removeAll()
- singleFaviconDownloaderCache.removeAll()
- }
-
- @objc func handleAppDidGoToBackground(_ notification: Notification) {
- cache.removeAll()
- singleFaviconDownloaderCache.removeAll()
- }
-
- public func favicon(for feed: Feed) -> IconImage? {
- assert(Thread.isMainThread)
-
+ /// Loading while a search through the home page’s favicons is downloading one.
+ public func favicon(for feed: Feed) -> IconLookup {
if shouldSkipDownloadingFavicon(feed: feed) {
- return nil
+ return .unavailable
}
-
- var homePageURL = feed.homePageURL
- if let faviconURL = feed.faviconURL {
- return favicon(with: faviconURL, homePageURL: homePageURL)
+ if let faviconURL = usableDeclaredFaviconURL(for: feed) {
+ feedsByDeclaredFaviconURL[faviconURL, default: Set()].insert(feed)
+ return iconImage(for: faviconURL, homePageURL: feed.homePageURL)
}
-
- if homePageURL == nil {
- // Base homePageURL off feedURL if needed. Won’t always be accurate, but is good enough.
- if let feedURL = URL(string: feed.url), let scheme = feedURL.scheme, let host = feedURL.host {
- homePageURL = scheme + "://" + host + "/"
- }
+ guard let homePageURL = faviconHomePageURL(for: feed) else {
+ return .unavailable
}
- if let homePageURL = homePageURL {
- return favicon(withHomePageURL: homePageURL)
- }
-
- return nil
- }
-
- public func faviconAsIcon(for feed: Feed) -> IconImage? {
-
- if let image = cache[feed] {
- return image
- }
-
- if let iconImage = favicon(for: feed) {
- cache[feed] = iconImage
- return iconImage
- }
-
- return nil
- }
-
- /// Returns the in-memory favicon for `feed` without triggering a download.
- public func cachedFaviconAsIcon(for feed: Feed) -> IconImage? {
- if let image = cache[feed] {
- return image
- }
- guard let faviconURL = cachedFaviconURL(for: feed) else {
- return nil
- }
- guard let iconImage = singleFaviconDownloaderCache[faviconURL]?.iconImage else {
- return nil
- }
- cache[feed] = iconImage
- return iconImage
- }
-
- /// The known favicon URL for `feed` (from feed settings or the home-page→favicon map), without
- /// triggering any download. Both lookups are in-memory, so this is cheap to call per row.
- public func cachedFaviconURL(for feed: Feed) -> String? {
- if let faviconURL = feed.faviconURL {
- return faviconURL
- }
- if let homePageURL = feed.homePageURL, let faviconURL = ImageMetadataDatabase.shared.faviconURL(forHomePageURL: homePageURL) {
- return faviconURL
- }
- return nil
- }
-
- public func favicon(with faviconURL: String, homePageURL: String?) -> IconImage? {
- guard canAttemptDownload(faviconURL) else {
- return nil
- }
- let downloader = faviconDownloader(withURL: faviconURL, homePageURL: homePageURL)
- return downloader.iconImage
- }
-
- public func favicon(withHomePageURL homePageURL: String) -> IconImage? {
-
- let url = homePageURL.normalizedURL
-
- if ImageMetadataDatabase.shared.homePageHasNoFavicon(url) {
- return nil
- }
-
- if let faviconURL = ImageMetadataDatabase.shared.faviconURL(forHomePageURL: url) {
- return favicon(with: faviconURL, homePageURL: url)
- }
-
- if let faviconURLs = findFaviconURLs(with: url) {
- // If the site explicitly specifies favicon.ico, it will appear twice.
- self.currentHomePageHasOnlyFaviconICO = faviconURLs.count == 1
- self.remainingFaviconURLs[url] = faviconURLs[...]
- downloadNextFavicon(forHomePageURL: url)
- }
-
- return nil
+ feedsByHomePageURL[homePageURL, default: Set()].insert(feed)
+ return favicon(forHomePageURL: homePageURL)
}
// MARK: - Notifications
- @objc func didLoadFavicon(_ note: Notification) {
-
- guard let singleFaviconDownloader = note.object as? SingleFaviconDownloader else {
+ /// Every home page searching with this favicon URL saves it.
+ @objc func handleIconImageDidBecomeAvailable(_ notification: Notification) {
+ guard let faviconURL = notification.userInfo?[IconImageDownloader.urlKey] as? String, faviconURLs.contains(faviconURL) else {
return
}
-
- // URL-level outcome runs before the homePageURL guard so we record it even when homePageURL is nil.
- if let error = singleFaviconDownloader.error {
- ImageMetadataDatabase.shared.recordFailure(url: singleFaviconDownloader.faviconURL, statusCode: error.statusCode)
- } else if singleFaviconDownloader.iconImage != nil {
- ImageMetadataDatabase.shared.clearFailure(url: singleFaviconDownloader.faviconURL)
+ faviconURLsThatAreNotImages.remove(faviconURL)
+ for homePageURL in homePageURLsSearching(with: faviconURL) {
+ saveFoundFavicon(faviconURL, homePageURL: homePageURL)
}
-
- guard let homePageURL = singleFaviconDownloader.homePageURL else {
- return
- }
- guard singleFaviconDownloader.iconImage != nil else {
- if remainingFaviconURLs[homePageURL] != nil {
- downloadNextFavicon(forHomePageURL: homePageURL)
- }
- return
- }
-
- remainingFaviconURLs[homePageURL] = nil
-
- postFaviconDidBecomeAvailableNotification(singleFaviconDownloader.faviconURL)
+ postFaviconDidChange(faviconURL)
}
- @objc func htmlMetadataIsAvailable(_ note: Notification) {
+ /// Every home page searching with this favicon URL moves on to its next candidate.
+ ///
+ /// When a saved favicon URL returns something that isn’t an image, the site may have moved its favicon,
+ /// so its home pages are searched again. The saved URL stays until a search finds another one,
+ /// so a captive portal can’t clear it.
+ @objc func handleIconImageDownloadDidFail(_ notification: Notification) {
+ guard let faviconURL = notification.userInfo?[IconImageDownloader.urlKey] as? String, faviconURLs.contains(faviconURL) else {
+ return
+ }
+ let error = notification.userInfo?[IconImageDownloader.errorKey] as? ImageDownloadError
- guard let url = note.userInfo?[HTMLMetadataUserInfoKey.url] as? String else {
+ for homePageURL in homePageURLsSearching(with: faviconURL) {
+ if error?.isTransient == true {
+ searches[homePageURL]?.hadTransientFailure = true
+ }
+ downloadNextFavicon(forHomePageURL: homePageURL)
+ }
+
+ if error?.decodingFailed == true {
+ faviconURLsThatAreNotImages.insert(faviconURL)
+ for homePageURL in ImageDatabase.shared.homePageURLs(withFaviconURL: faviconURL) {
+ searchForFavicon(homePageURL: homePageURL)
+ }
+ }
+ }
+
+ /// Waits for transient failures may have just ended, so searches that had one are tried again.
+ /// `IconImageDownloader` tries favicons that failed transiently again on this notification too.
+ @objc func handleNetworkStatusDidChange(_ notification: Notification) {
+ guard NetworkMonitor.shared.isConnected else {
+ return
+ }
+ Task { @MainActor in
+ let homePageURLs = homePagesWithTransientSearchFailure
+ homePagesWithTransientSearchFailure.removeAll()
+ for homePageURL in homePageURLs {
+ searchForFavicon(homePageURL: homePageURL)
+ }
+ }
+ }
+
+ /// A favicon already in memory posts nothing when it’s looked up again, so it’s posted here.
+ @objc func handleFeedSettingDidChange(_ notification: Notification) {
+ guard let feed = notification.object as? Feed, let key = notification.userInfo?[Feed.SettingUserInfoKey] as? Feed.SettingKey else {
+ return
+ }
+ guard key == .faviconURL || key == .homePageURL else {
+ return
+ }
+ postFaviconDidChange(Set([feed]))
+ }
+
+ /// New metadata may name a different favicon.
+ @objc func handleHTMLMetadataAvailable(_ notification: Notification) {
+ guard let homePageURL = notification.userInfo?[HTMLMetadataUserInfoKey.url] as? String else {
assertionFailure("Expected URL string in .htmlMetadataAvailable Notification userInfo.")
return
}
+ guard homePagesLookedUp.contains(homePageURL) else {
+ return
+ }
Task { @MainActor in
- _ = favicon(withHomePageURL: url)
+ homePagesCheckedForNewFavicon.remove(homePageURL)
+ if homePagesAwaitingMetadataForSearch.remove(homePageURL) != nil {
+ searchForFavicon(homePageURL: homePageURL)
+ } else {
+ _ = favicon(forHomePageURL: homePageURL)
+ }
}
}
}
@@ -207,10 +157,63 @@ private extension FaviconDownloader {
static let specialCasesToSkip = [SpecialCase.rachelByTheBayHostName, SpecialCase.openRSSOrgHostName]
+ /// A home page’s favicon URLs are tried in order until one works.
+ struct FaviconSearch {
+ var remainingFaviconURLs: ArraySlice
+ var faviconURL: String? // Being downloaded
+ var hadTransientFailure = false
+ /// A search for a better favicon than the saved one, which keeps working if none is found.
+ var keepsSavedFavicon = false
+ }
+
func shouldSkipDownloadingFavicon(feed: Feed) -> Bool {
SpecialCase.urlStringContainSpecialCase(feed.url, Self.specialCasesToSkip)
}
+ func favicon(forHomePageURL homePageURL: String) -> IconLookup {
+ homePagesLookedUp.insert(homePageURL)
+
+ if ImageDatabase.shared.homePageHasNoFavicon(homePageURL) {
+ return .unavailable
+ }
+
+ // A saved favicon that keeps failing is searched for again, in case the site moved it.
+ if let faviconURL = ImageDatabase.shared.faviconURL(forHomePageURL: homePageURL), !ImageDatabase.shared.recentlyFailed(url: faviconURL) {
+ checkForNewFaviconURL(homePageURL: homePageURL, savedFaviconURL: faviconURL)
+ return iconImage(for: faviconURL, homePageURL: homePageURL)
+ }
+
+ searchForFavicon(homePageURL: homePageURL)
+ return searches[homePageURL] == nil ? .unavailable : .loading
+ }
+
+ func iconImage(for faviconURL: String, homePageURL: String?) -> IconLookup {
+ faviconURLs.insert(faviconURL)
+ return IconImageDownloader.shared.iconImage(for: faviconURL, activityOwner: .faviconDownloader, activityKind: .downloadFavicon(faviconURL: faviconURL), activityDetail: homePageURL)
+ }
+
+ /// The favicon URL the feed specifies, unless it recently failed or isn’t an image,
+ /// in which case the home page’s favicon is used instead.
+ /// Called per row, so it doesn’t log the way `canAttemptDownload` does.
+ func usableDeclaredFaviconURL(for feed: Feed) -> String? {
+ guard let faviconURL = feed.faviconURL, faviconURL.hasPrefix("http://") || faviconURL.hasPrefix("https://"), !ImageDatabase.shared.recentlyFailed(url: faviconURL), !faviconURLsThatAreNotImages.contains(faviconURL) else {
+ return nil
+ }
+ return faviconURL
+ }
+
+ /// The home page that favicons are saved under: the feed’s home page, or else the feed URL’s scheme and host.
+ func faviconHomePageURL(for feed: Feed) -> String? {
+ if let homePageURL = feed.homePageURL {
+ return homePageURL.normalizedURL
+ }
+ // Won’t always be the real home page, but is good enough.
+ guard let feedURL = URL(string: feed.url), let scheme = feedURL.scheme, let host = feedURL.host else {
+ return nil
+ }
+ return (scheme + "://" + host + "/").normalizedURL
+ }
+
static let localeForLowercasing = Locale(identifier: "en_US")
func findFaviconURLs(with homePageURL: String) -> [String]? {
@@ -231,66 +234,115 @@ private extension FaviconDownloader {
return faviconURLs + [defaultFaviconURL]
}
+ func homePageURLsSearching(with faviconURL: String) -> [String] {
+ searches.filter { $0.value.faviconURL == faviconURL }.map { $0.key }
+ }
+
+ /// Without the home page’s metadata in memory, the search starts when `.htmlMetadataAvailable` arrives.
+ func searchForFavicon(homePageURL: String) {
+ guard searches[homePageURL] == nil else {
+ return
+ }
+ guard let faviconURLs = findFaviconURLs(with: homePageURL) else {
+ homePagesAwaitingMetadataForSearch.insert(homePageURL)
+ return
+ }
+ searches[homePageURL] = FaviconSearch(remainingFaviconURLs: faviconURLs[...])
+ downloadNextFavicon(forHomePageURL: homePageURL)
+ }
+
+ /// The saved favicon keeps working after a site adds or moves its favicon, so once per session,
+ /// and again when the home page’s metadata arrives, the candidates ahead of the saved one are tried.
+ func checkForNewFaviconURL(homePageURL: String, savedFaviconURL: String) {
+ guard !homePagesCheckedForNewFavicon.contains(homePageURL), searches[homePageURL] == nil else {
+ return
+ }
+ homePagesCheckedForNewFavicon.insert(homePageURL)
+ guard let faviconURLs = findFaviconURLs(with: homePageURL) else {
+ return
+ }
+ let betterFaviconURLs = faviconURLs.prefix { $0 != savedFaviconURL }
+ guard !betterFaviconURLs.isEmpty else {
+ return
+ }
+ searches[homePageURL] = FaviconSearch(remainingFaviconURLs: betterFaviconURLs, keepsSavedFavicon: true)
+ downloadNextFavicon(forHomePageURL: homePageURL)
+ }
+
func canAttemptDownload(_ faviconURL: String) -> Bool {
if !faviconURL.hasPrefix("http://") && !faviconURL.hasPrefix("https://") {
Self.logger.debug("Skipping non-http(s) URL: \(faviconURL)")
return false
}
- if ImageMetadataDatabase.shared.recentlyFailed(url: faviconURL) {
+ if ImageDatabase.shared.recentlyFailed(url: faviconURL) {
Self.logger.debug("Skipping recently-failed URL: \(faviconURL)")
return false
}
return true
}
- // A skipped candidate advances to the next one — otherwise the queue
- // would stall and the remaining candidates would never be tried.
- //
+ /// A skipped candidate advances to the next one — otherwise the search
+ /// would stall and the remaining candidates would never be tried.
+ ///
+ ///
+ /// Without a transient failure, a search that runs out of candidates saves that the home page has no favicon.
func downloadNextFavicon(forHomePageURL homePageURL: String) {
- while let faviconURL = remainingFaviconURLs[homePageURL]?.first {
- remainingFaviconURLs[homePageURL] = remainingFaviconURLs[homePageURL]?.dropFirst()
- if canAttemptDownload(faviconURL) {
- _ = faviconDownloader(withURL: faviconURL, homePageURL: homePageURL)
+ while var search = searches[homePageURL], let faviconURL = search.remainingFaviconURLs.first {
+ search.remainingFaviconURLs = search.remainingFaviconURLs.dropFirst()
+ search.faviconURL = nil
+ searches[homePageURL] = search
+ guard canAttemptDownload(faviconURL) else {
+ continue
+ }
+
+ switch iconImage(for: faviconURL, homePageURL: homePageURL) {
+ case .found:
+ // Already in memory, such as for another home page on the same site, so no `.iconImageDidBecomeAvailable` is coming.
+ saveFoundFavicon(faviconURL, homePageURL: homePageURL)
+ postFaviconDidChange(faviconURL)
return
+ case .loading:
+ searches[homePageURL]?.faviconURL = faviconURL
+ return
+ case .unavailable:
+ // Failed earlier in this session, and isn’t due to be tried again yet.
+ if DownloadedImageCache.shared.isWaitingToRetry(faviconURL) {
+ searches[homePageURL]?.hadTransientFailure = true
+ }
}
}
- remainingFaviconURLs[homePageURL] = nil
- if currentHomePageHasOnlyFaviconICO {
- ImageMetadataDatabase.shared.saveHomePageFavicon(homePageURL: homePageURL, faviconURL: nil)
+ guard let search = searches.removeValue(forKey: homePageURL) else {
+ return
+ }
+ if search.hadTransientFailure {
+ homePagesWithTransientSearchFailure.insert(homePageURL)
+ } else if !search.keepsSavedFavicon {
+ ImageDatabase.shared.saveHomePageFavicon(homePageURL: homePageURL, faviconURL: nil)
}
}
- func faviconDownloader(withURL faviconURL: String, homePageURL: String?) -> SingleFaviconDownloader {
-
- var firstTimeSeeingHomepageURL = false
-
- if let homePageURL, ImageMetadataDatabase.shared.faviconURL(forHomePageURL: homePageURL) == nil {
- ImageMetadataDatabase.shared.saveHomePageFavicon(homePageURL: homePageURL, faviconURL: faviconURL)
- firstTimeSeeingHomepageURL = true
- }
-
- if let downloader = singleFaviconDownloaderCache[faviconURL] {
- if firstTimeSeeingHomepageURL && !downloader.downloadFaviconIfNeeded() {
- // This is to handle the scenario where we have different homepages, but the same favicon.
- // This happens for Twitter and probably other sites like Blogger. Because the favicon
- // is cached, we wouldn't send out a notification that it is now available unless we send
- // it here.
- postFaviconDidBecomeAvailableNotification(faviconURL)
- }
- return downloader
- }
-
- let downloader = SingleFaviconDownloader(faviconURL: faviconURL, homePageURL: homePageURL, diskCache: diskCache, queue: queue)
- singleFaviconDownloaderCache[faviconURL] = downloader
- return downloader
+ /// Feeds showing the previous favicon get the new one on their next lookup.
+ func saveFoundFavicon(_ faviconURL: String, homePageURL: String) {
+ searches[homePageURL] = nil
+ ImageDatabase.shared.saveHomePageFavicon(homePageURL: homePageURL, faviconURL: faviconURL)
}
- func postFaviconDidBecomeAvailableNotification(_ faviconURL: String) {
+ func postFaviconDidChange(_ faviconURL: String) {
+ var feedsUsingFavicon = feedsByDeclaredFaviconURL[faviconURL] ?? Set()
+ for (homePageURL, feeds) in feedsByHomePageURL where ImageDatabase.shared.faviconURL(forHomePageURL: homePageURL) == faviconURL {
+ feedsUsingFavicon.formUnion(feeds)
+ }
+ guard !feedsUsingFavicon.isEmpty else {
+ return
+ }
+ postFaviconDidChange(feedsUsingFavicon)
+ }
+ /// Posted later, since a lookup can find a favicon already in memory.
+ func postFaviconDidChange(_ feeds: Set) {
DispatchQueue.main.async {
- let userInfo: [AnyHashable: Any] = [UserInfoKey.faviconURL: faviconURL]
- NotificationCenter.default.post(name: .FaviconDidBecomeAvailable, object: self, userInfo: userInfo)
+ NotificationCenter.default.post(name: .faviconDidChange, object: self, userInfo: [Self.feedsKey: feeds])
}
}
}
diff --git a/Modules/Images/Sources/Images/FaviconGenerator.swift b/Modules/Images/Sources/Images/FaviconGenerator.swift
index d4e0a6082..ff8a1f44d 100644
--- a/Modules/Images/Sources/Images/FaviconGenerator.swift
+++ b/Modules/Images/Sources/Images/FaviconGenerator.swift
@@ -19,7 +19,7 @@ import Account
private var cache = [String: IconImage]() // feedURL: IconImage
- init() {
+ private init() {
NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
}
diff --git a/Modules/Images/Sources/Images/FeedIconDownloader.swift b/Modules/Images/Sources/Images/FeedIconDownloader.swift
index ee2a42dac..a486454ac 100644
--- a/Modules/Images/Sources/Images/FeedIconDownloader.swift
+++ b/Modules/Images/Sources/Images/FeedIconDownloader.swift
@@ -10,173 +10,68 @@ import Foundation
import Account
import RSCore
import RSWeb
-import HTMLMetadata
import ActivityLog
extension Notification.Name {
-
- public static let feedIconDidBecomeAvailable = Notification.Name("FeedIconDidBecomeAvailable") // userInfo key: "feed"
+ /// Posted when a feed’s icon loads or fails, or its icon URL changes.
+ /// userInfo key: `FeedIconDownloader.feedsKey` (`Set`).
+ public static let feedIconDidChange = Notification.Name("FeedIconDidChange")
}
+/// Gets the icon a feed specifies in the feed itself.
@MainActor public final class FeedIconDownloader {
public static let shared = FeedIconDownloader()
+ public static let feedsKey = "feeds"
- private let imageDownloader = ImageDownloader.shared
- private var homePagesWithNoIconURL = Set()
- private var cache = [Feed: IconImage]()
- private var waitingForFeedURLs = [String: Set]()
- private var feedsWaitingForHTMLMetadata = Set()
+ private var feedsByIconURL = [String: Set]() // icon URL: feeds that looked it up
- init() {
- NotificationCenter.default.addObserver(self, selector: #selector(imageDidBecomeAvailable(_:)), name: .imageDidBecomeAvailable, object: imageDownloader)
+ private init() {
+ NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDidBecomeAvailable(_:)), name: .iconImageDidBecomeAvailable, object: IconImageDownloader.shared)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDownloadDidFail(_:)), name: .iconImageDownloadDidFail, object: IconImageDownloader.shared)
NotificationCenter.default.addObserver(self, selector: #selector(handleFeedSettingDidChange(_:)), name: .feedSettingDidChange, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(handleHTMLMetadataAvailable(_:)), name: .htmlMetadataAvailable, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
}
- @objc func handleLowMemory(_ notification: Notification) {
- cache.removeAll()
+ /// Unavailable when the feed specifies no icon, or its icon isn’t used.
+ public func feedIcon(for feed: Feed) -> IconLookup {
+ guard let iconURL = Self.iconURL(for: feed) else {
+ return .unavailable
+ }
+ feedsByIconURL[iconURL, default: Set()].insert(feed)
+ return IconImageDownloader.shared.iconImage(for: iconURL, activityOwner: .feedImageDownloader, activityKind: .downloadFeedImage(feedURL: iconURL), activityDetail: feed.nameForDisplay)
}
- @objc func handleAppDidGoToBackground(_ notification: Notification) {
- cache.removeAll()
+ // MARK: - Notifications
+
+ @objc func handleIconImageDidBecomeAvailable(_ notification: Notification) {
+ postFeedIconDidChange(iconURL: notification.userInfo?[IconImageDownloader.urlKey] as? String)
}
- public func icon(for feed: Feed) -> IconImage? {
-
- if let cachedImage = cache[feed] {
- return cachedImage
- }
-
- if Self.shouldSkipDownloadingFeedIcon(feed: feed) {
- return nil
- }
-
- @MainActor func checkHomePageURL() {
- guard let homePageURL = feed.homePageURL else {
- return
- }
- if homePagesWithNoIconURL.contains(homePageURL) {
- return
- }
- icon(forHomePageURL: homePageURL, feed: feed) { image, iconURL in
- if self.cache[feed] != nil {
- return // already cached
- }
- if let image, let iconURL {
- self.cache[feed] = IconImage(image)
- self.cacheIconURLForFeedURL(iconURL: iconURL, feedURL: feed.url)
- self.postFeedIconDidBecomeAvailableNotification(feed)
- }
- }
- }
-
- @MainActor func checkFeedIconURL() {
- if let iconURL = feed.iconURL, !Self.shouldIgnoreFeedIconURL(feed) {
- icon(forURL: iconURL, feed: feed) { (image, isDefinitive) in
- Task { @MainActor in
- if self.cache[feed] != nil {
- return // already cached
- }
- if let image = image {
- self.cache[feed] = IconImage(image)
- self.cacheIconURLForFeedURL(iconURL: iconURL, feedURL: feed.url)
- self.postFeedIconDidBecomeAvailableNotification(feed)
- } else if isDefinitive {
- // The declared icon failed or isn’t an image. A still-downloading
- // icon is no reason to fall back to the home page’s icon.
- //
- checkHomePageURL()
- }
- }
- }
- } else {
- checkHomePageURL()
- }
- }
-
- // The stored icon URL remembers an icon discovered via the home page. A feed
- // that declares its own icon supersedes it.
- //
- let feedDeclaresIconURL = feed.iconURL != nil && !Self.shouldIgnoreFeedIconURL(feed)
-
- if !feedDeclaresIconURL, let previouslyFoundIconURL = ImageMetadataDatabase.shared.iconURL(forFeedURL: feed.url) {
- icon(forURL: previouslyFoundIconURL, feed: feed) { image, _ in
- if self.cache[feed] != nil {
- return // already cached
- }
- if let image {
- self.cache[feed] = IconImage(image)
- self.postFeedIconDidBecomeAvailableNotification(feed)
- }
- }
-
- return nil
- }
-
- checkFeedIconURL()
-
- return nil
+ @objc func handleIconImageDownloadDidFail(_ notification: Notification) {
+ postFeedIconDidChange(iconURL: notification.userInfo?[IconImageDownloader.urlKey] as? String)
}
- @objc func imageDidBecomeAvailable(_ note: Notification) {
- guard let url = note.userInfo?["url"] as? String, let feeds = waitingForFeedURLs[url] else {
+ @objc func handleFeedSettingDidChange(_ notification: Notification) {
+ guard let feed = notification.object as? Feed, let key = notification.userInfo?[Feed.SettingUserInfoKey] as? Feed.SettingKey, key == .iconURL else {
return
}
- // A single image URL may be shared by multiple feeds.
- waitingForFeedURLs[url] = nil
- for feed in feeds {
- _ = icon(for: feed)
- }
- }
-
- @objc func handleFeedSettingDidChange(_ note: Notification) {
- guard let feed = note.object as? Feed, let key = note.userInfo?[Feed.SettingUserInfoKey] as? Feed.SettingKey else {
- return
- }
- if key == .iconURL || key == .homePageURL {
- _ = icon(for: feed)
- }
- }
-
- @objc func handleHTMLMetadataAvailable(_ note: Notification) {
- guard let url = note.userInfo?[HTMLMetadataUserInfoKey.url] as? String else {
- return
- }
- // A homepage URL may be shared by multiple feeds.
- let feeds = feedsWaitingForHTMLMetadata.filter { $0.homePageURL == url }
- feedsWaitingForHTMLMetadata.subtract(feeds)
- for feed in feeds {
- _ = icon(for: feed)
- }
- }
-
- /// Returns the in-memory icon for `feed` without triggering a download.
- public func cachedIcon(for feed: Feed) -> IconImage? {
- cache[feed]
+ postFeedIconDidChange(Set([feed]))
}
}
private extension FeedIconDownloader {
- static let specialCasesToSkip = ["macsparky.com", "xkcd.com", SpecialCase.rachelByTheBayHostName, SpecialCase.openRSSOrgHostName]
-
- // Substrings matched (case-insensitive) anywhere in the feed URL. A match makes us ignore the
- // feed-specified icon URL and fall back to the homepage icon lookup instead.
+ // Substrings matched (case-insensitive) anywhere in the feed URL. A match means the feed-specified icon isn’t used.
static let feedURLSubstringsToIgnoreFeedIconURL: [String] = ["propublica.org", "clubic.com", "comptoir-hardware.com", "cowcotland", "404media.co", "awfulannouncing.com", "michalzelazny.com"]
- static func shouldIgnoreFeedIconURL(_ feed: Feed) -> Bool {
- SpecialCase.urlStringContainSpecialCase(feed.url, feedURLSubstringsToIgnoreFeedIconURL)
- }
-
- static func shouldSkipDownloadingFeedIcon(feed: Feed) -> Bool {
- shouldSkipDownloadingFeedIcon(feed.url)
- }
-
- static func shouldSkipDownloadingFeedIcon(_ urlString: String) -> Bool {
- SpecialCase.urlStringContainSpecialCase(urlString, specialCasesToSkip)
+ static func iconURL(for feed: Feed) -> String? {
+ guard let iconURL = feed.iconURL else {
+ return nil
+ }
+ if SpecialCase.urlStringContainSpecialCase(feed.url, SpecialCase.hostNamesWithoutFeedOrHomePageIcons) || SpecialCase.urlStringContainSpecialCase(feed.url, feedURLSubstringsToIgnoreFeedIconURL) {
+ return nil
+ }
+ return sanitizedIconURL(iconURL)
}
static func sanitizedIconURL(_ url: String) -> String {
@@ -193,70 +88,14 @@ private extension FeedIconDownloader {
return components.string ?? url
}
- func icon(forHomePageURL homePageURL: String, feed: Feed, _ resultBlock: @escaping @MainActor (RSImage?, String?) -> Void) {
- if Self.shouldSkipDownloadingFeedIcon(homePageURL) {
- resultBlock(nil, nil)
+ func postFeedIconDidChange(iconURL: String?) {
+ guard let iconURL, let feeds = feedsByIconURL[iconURL] else {
return
}
-
- if homePagesWithNoIconURL.contains(homePageURL) {
- resultBlock(nil, nil)
- return
- }
-
- guard let metadata = HTMLMetadataDownloader.shared.cachedMetadata(for: homePageURL) else {
- feedsWaitingForHTMLMetadata.insert(feed)
- resultBlock(nil, nil)
- return
- }
-
- if let url = metadata.bestWebsiteIconURL() {
- homePagesWithNoIconURL.remove(homePageURL)
- icon(forURL: url, feed: feed) { image, _ in
- Task { @MainActor in
- resultBlock(image, url)
- }
- }
- return
- }
-
- homePagesWithNoIconURL.insert(homePageURL)
- resultBlock(nil, nil)
+ postFeedIconDidChange(feeds)
}
- /// `isDefinitive` is false when the image is still downloading — imageDidBecomeAvailable
- /// re-runs icon(for:) when it arrives.
- func icon(forURL url: String, feed: Feed, _ imageResultBlock: @escaping @MainActor (RSImage?, _ isDefinitive: Bool) -> Void) {
-
- let url = Self.sanitizedIconURL(url)
-
- let kind = ActivityKind.downloadFeedImage(feedURL: url)
- if let imageData = imageDownloader.image(for: url, activityOwner: .feedImageDownloader, activityKind: kind, activityDetail: feed.nameForDisplay) {
- RSImage.image(with: imageData) { image in
- imageResultBlock(image, true)
- }
- return
- }
-
- let urlIsUnfetchable = !url.hasPrefix("http://") && !url.hasPrefix("https://")
- if urlIsUnfetchable || ImageMetadataDatabase.shared.recentlyFailed(url: url) {
- imageResultBlock(nil, true)
- return
- }
-
- waitingForFeedURLs[url, default: Set()].insert(feed)
- imageResultBlock(nil, false)
- }
-
- func postFeedIconDidBecomeAvailableNotification(_ feed: Feed) {
-
- DispatchQueue.main.async {
- let userInfo: [AnyHashable: Any] = ["feed": feed]
- NotificationCenter.default.post(name: .feedIconDidBecomeAvailable, object: self, userInfo: userInfo)
- }
- }
-
- func cacheIconURLForFeedURL(iconURL: String, feedURL: String) {
- ImageMetadataDatabase.shared.saveFeedIconURL(feedURL: feedURL, iconURL: iconURL)
+ func postFeedIconDidChange(_ feeds: Set) {
+ NotificationCenter.default.post(name: .feedIconDidChange, object: self, userInfo: [Self.feedsKey: feeds])
}
}
diff --git a/Modules/Images/Sources/Images/FeedIconURLTable.swift b/Modules/Images/Sources/Images/FeedIconURLTable.swift
deleted file mode 100644
index 2980ebcbc..000000000
--- a/Modules/Images/Sources/Images/FeedIconURLTable.swift
+++ /dev/null
@@ -1,48 +0,0 @@
-//
-// FeedIconURLTable.swift
-// Images
-//
-// Created by Brent Simmons on 5/28/26.
-//
-
-import Foundation
-import RSDatabase
-import RSDatabaseObjC
-
-struct FeedIconURLTable {
-
- static let name = "feedIconURL"
-
- private struct Column {
- static let feedURL = "feedURL"
- static let iconURL = "iconURL"
- static let lastChecked = "lastChecked"
- }
-
- static func fetchAll(database: FMDatabase) -> [String: String] {
- var results = [String: String]()
- guard let resultSet = database.executeQuery("SELECT \(Column.feedURL), \(Column.iconURL) FROM \(name);", withArgumentsIn: []) else {
- return results
- }
- defer {
- resultSet.close()
- }
- while resultSet.next() {
- guard let feedURL = resultSet.string(forColumn: Column.feedURL),
- let iconURL = resultSet.string(forColumn: Column.iconURL) else {
- continue
- }
- results[feedURL] = iconURL
- }
- return results
- }
-
- static func save(feedURL: String, iconURL: String, database: FMDatabase) {
- let dictionary: DatabaseDictionary = [
- Column.feedURL: feedURL,
- Column.iconURL: iconURL,
- Column.lastChecked: Date().timeIntervalSince1970
- ]
- database.insertRow(dictionary, insertType: .orReplace, tableName: name)
- }
-}
diff --git a/Modules/Images/Sources/Images/HomePageFaviconTable.swift b/Modules/Images/Sources/Images/HomePageFaviconTable.swift
index f69980905..3f88ca5f7 100644
--- a/Modules/Images/Sources/Images/HomePageFaviconTable.swift
+++ b/Modules/Images/Sources/Images/HomePageFaviconTable.swift
@@ -10,10 +10,10 @@ import RSDatabase
import RSDatabaseObjC
/// `faviconURL` is `nil` when the homepage has no usable favicon.
-public struct HomePageFaviconRecord: Sendable {
- public let homePageURL: String
- public let faviconURL: String?
- public let lastChecked: Date
+struct HomePageFaviconRecord: Sendable {
+ let homePageURL: String
+ let faviconURL: String?
+ let lastChecked: Date
}
struct HomePageFaviconTable {
diff --git a/Modules/Images/Sources/Images/HomePageIconDownloader.swift b/Modules/Images/Sources/Images/HomePageIconDownloader.swift
new file mode 100644
index 000000000..6863d53d1
--- /dev/null
+++ b/Modules/Images/Sources/Images/HomePageIconDownloader.swift
@@ -0,0 +1,168 @@
+//
+// HomePageIconDownloader.swift
+// Images
+//
+// Created by Brent Simmons on 11/3/26.
+//
+
+import Foundation
+import Account
+import RSCore
+import RSWeb
+import HTMLMetadata
+import ActivityLog
+
+extension Notification.Name {
+ /// Posted when a home page’s icon loads or fails, or its icon URL changes.
+ /// userInfo key: `HomePageIconDownloader.feedsKey` (`Set`, the feeds that looked up that home page).
+ public static let homePageIconDidChange = Notification.Name("HomePageIconDidChange")
+}
+
+/// Gets the icon a feed’s home page specifies in its metadata: an apple-touch-icon, og:image, or twitter:image.
+///
+/// The icon URL is saved, so it works at launch, before the home page’s metadata is in memory.
+/// A site may add, change, or move its icon, so once per session, and whenever the home page’s metadata
+/// arrives, a different icon URL in the metadata replaces the saved one once its image loads.
+@MainActor public final class HomePageIconDownloader {
+
+ public static let shared = HomePageIconDownloader()
+ public static let feedsKey = "feeds"
+
+ private var feedsByHomePageURL = [String: Set]() // home page URL: feeds that looked it up
+ private var homePagesCheckedForNewIconURL = Set()
+ private var newIconURLs = [String: String]() // home page URL: icon URL that replaces the saved one once its image loads
+ private var iconURLs = Set() // Every icon URL looked up, so other kinds of icons are ignored when they arrive
+
+ private init() {
+ NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDidBecomeAvailable(_:)), name: .iconImageDidBecomeAvailable, object: IconImageDownloader.shared)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleIconImageDownloadDidFail(_:)), name: .iconImageDownloadDidFail, object: IconImageDownloader.shared)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleHTMLMetadataAvailable(_:)), name: .htmlMetadataAvailable, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleFeedSettingDidChange(_:)), name: .feedSettingDidChange, object: nil)
+ }
+
+ /// Unavailable while the home page’s metadata isn’t in memory. `.homePageIconDidChange` follows when it arrives.
+ public func homePageIcon(for feed: Feed) -> IconLookup {
+ guard let homePageURL = Self.homePageURL(for: feed) else {
+ return .unavailable
+ }
+ feedsByHomePageURL[homePageURL, default: Set()].insert(feed)
+
+ if let savedIconURL = ImageDatabase.shared.homePageIconURL(forHomePageURL: homePageURL) {
+ if homePagesCheckedForNewIconURL.insert(homePageURL).inserted {
+ checkForNewIconURL(homePageURL: homePageURL, savedIconURL: savedIconURL)
+ }
+ return iconImage(for: savedIconURL, homePageURL: homePageURL)
+ }
+
+ if ImageDatabase.shared.homePageHasNoIcon(homePageURL) {
+ return .unavailable
+ }
+ guard let iconURL = iconURLFromMetadata(homePageURL: homePageURL) else {
+ return .unavailable
+ }
+ return iconImage(for: iconURL, homePageURL: homePageURL)
+ }
+
+ // MARK: - Notifications
+
+ @objc func handleIconImageDidBecomeAvailable(_ notification: Notification) {
+ guard let iconURL = notification.userInfo?[IconImageDownloader.urlKey] as? String, iconURLs.contains(iconURL) else {
+ return
+ }
+ for (homePageURL, newIconURL) in newIconURLs where newIconURL == iconURL {
+ newIconURLs[homePageURL] = nil
+ ImageDatabase.shared.saveHomePageIcon(homePageURL: homePageURL, iconURL: newIconURL)
+ }
+ postHomePageIconDidChange(iconURL: iconURL)
+ }
+
+ /// Feeds showing this icon look again, which falls back to the next source.
+ @objc func handleIconImageDownloadDidFail(_ notification: Notification) {
+ guard let iconURL = notification.userInfo?[IconImageDownloader.urlKey] as? String, iconURLs.contains(iconURL) else {
+ return
+ }
+ newIconURLs = newIconURLs.filter { $0.value != iconURL }
+ postHomePageIconDidChange(iconURL: iconURL)
+ }
+
+ @objc func handleHTMLMetadataAvailable(_ notification: Notification) {
+ guard let homePageURL = notification.userInfo?[HTMLMetadataUserInfoKey.url] as? String, feedsByHomePageURL[homePageURL] != nil else {
+ return
+ }
+ homePagesCheckedForNewIconURL.insert(homePageURL)
+ if let savedIconURL = ImageDatabase.shared.homePageIconURL(forHomePageURL: homePageURL) {
+ checkForNewIconURL(homePageURL: homePageURL, savedIconURL: savedIconURL)
+ } else if iconURLFromMetadata(homePageURL: homePageURL) != nil {
+ postHomePageIconDidChange(homePageURL: homePageURL)
+ }
+ }
+
+ @objc func handleFeedSettingDidChange(_ notification: Notification) {
+ guard let feed = notification.object as? Feed, let key = notification.userInfo?[Feed.SettingUserInfoKey] as? Feed.SettingKey, key == .homePageURL else {
+ return
+ }
+ NotificationCenter.default.post(name: .homePageIconDidChange, object: self, userInfo: [Self.feedsKey: Set([feed])])
+ }
+}
+
+private extension HomePageIconDownloader {
+
+ static func homePageURL(for feed: Feed) -> String? {
+ guard let homePageURL = feed.homePageURL else {
+ return nil
+ }
+ if SpecialCase.urlStringContainSpecialCase(feed.url, SpecialCase.hostNamesWithoutFeedOrHomePageIcons) || SpecialCase.urlStringContainSpecialCase(homePageURL, SpecialCase.hostNamesWithoutFeedOrHomePageIcons) {
+ return nil
+ }
+ return homePageURL.normalizedURL
+ }
+
+ /// Saves the icon URL, or that there is none. Nil when the metadata isn’t in memory,
+ /// in which case this starts loading it, and `.htmlMetadataAvailable` follows.
+ func iconURLFromMetadata(homePageURL: String) -> String? {
+ guard let metadata = HTMLMetadataDownloader.shared.cachedMetadata(for: homePageURL) else {
+ return nil
+ }
+ let iconURL = metadata.bestHomePageIconURL()
+ ImageDatabase.shared.saveHomePageIcon(homePageURL: homePageURL, iconURL: iconURL)
+ return iconURL
+ }
+
+ /// The saved icon keeps working if the new one fails, or if the metadata no longer specifies an icon.
+ func checkForNewIconURL(homePageURL: String, savedIconURL: String) {
+ guard let metadata = HTMLMetadataDownloader.shared.cachedMetadata(for: homePageURL), let iconURL = metadata.bestHomePageIconURL(), iconURL != savedIconURL else {
+ return
+ }
+ switch iconImage(for: iconURL, homePageURL: homePageURL) {
+ case .found:
+ ImageDatabase.shared.saveHomePageIcon(homePageURL: homePageURL, iconURL: iconURL)
+ // Called during a lookup, so the change is posted afterward.
+ Task { @MainActor in
+ postHomePageIconDidChange(homePageURL: homePageURL)
+ }
+ case .loading:
+ // When it loads, `handleIconImageDidBecomeAvailable` saves it.
+ newIconURLs[homePageURL] = iconURL
+ case .unavailable:
+ break
+ }
+ }
+
+ func iconImage(for iconURL: String, homePageURL: String) -> IconLookup {
+ iconURLs.insert(iconURL)
+ return IconImageDownloader.shared.iconImage(for: iconURL, activityOwner: .feedImageDownloader, activityKind: .downloadFeedImage(feedURL: iconURL), activityDetail: homePageURL)
+ }
+
+ func postHomePageIconDidChange(iconURL: String) {
+ for homePageURL in feedsByHomePageURL.keys where ImageDatabase.shared.homePageIconURL(forHomePageURL: homePageURL) == iconURL {
+ postHomePageIconDidChange(homePageURL: homePageURL)
+ }
+ }
+
+ func postHomePageIconDidChange(homePageURL: String) {
+ guard let feeds = feedsByHomePageURL[homePageURL] else {
+ return
+ }
+ NotificationCenter.default.post(name: .homePageIconDidChange, object: self, userInfo: [Self.feedsKey: feeds])
+ }
+}
diff --git a/Modules/Images/Sources/Images/HomePageIconTable.swift b/Modules/Images/Sources/Images/HomePageIconTable.swift
new file mode 100644
index 000000000..cc91f3ce3
--- /dev/null
+++ b/Modules/Images/Sources/Images/HomePageIconTable.swift
@@ -0,0 +1,56 @@
+//
+// HomePageIconTable.swift
+// Images
+//
+// Created by Brent Simmons on 5/28/26.
+//
+
+import Foundation
+import RSDatabase
+import RSDatabaseObjC
+
+/// `iconURL` is `nil` when the home page’s metadata specifies no icon.
+struct HomePageIconRecord: Sendable {
+ let homePageURL: String
+ let iconURL: String?
+ let lastChecked: Date
+}
+
+struct HomePageIconTable {
+
+ static let name = "homePageIcon"
+
+ private struct Column {
+ static let homePageURL = "homePageURL"
+ static let iconURL = "iconURL"
+ static let lastChecked = "lastChecked"
+ }
+
+ static func fetchAll(database: FMDatabase) -> [HomePageIconRecord] {
+ var results = [HomePageIconRecord]()
+ guard let resultSet = database.executeQuery("SELECT \(Column.homePageURL), \(Column.iconURL), \(Column.lastChecked) FROM \(name);", withArgumentsIn: []) else {
+ return results
+ }
+ defer {
+ resultSet.close()
+ }
+ while resultSet.next() {
+ guard let homePageURL = resultSet.string(forColumn: Column.homePageURL) else {
+ continue
+ }
+ let iconURL = resultSet.string(forColumn: Column.iconURL)
+ let lastChecked = Date(timeIntervalSince1970: resultSet.double(forColumn: Column.lastChecked))
+ results.append(HomePageIconRecord(homePageURL: homePageURL, iconURL: iconURL, lastChecked: lastChecked))
+ }
+ return results
+ }
+
+ static func save(homePageURL: String, iconURL: String?, database: FMDatabase) {
+ let dictionary: DatabaseDictionary = [
+ Column.homePageURL: homePageURL,
+ Column.iconURL: iconURL as Any,
+ Column.lastChecked: Date().timeIntervalSince1970
+ ]
+ database.insertRow(dictionary, insertType: .orReplace, tableName: name)
+ }
+}
diff --git a/Modules/Images/Sources/Images/IconImage.swift b/Modules/Images/Sources/Images/IconImage.swift
index 2174033f8..df12f5182 100644
--- a/Modules/Images/Sources/Images/IconImage.swift
+++ b/Modules/Images/Sources/Images/IconImage.swift
@@ -11,7 +11,7 @@ import AppKit
#else
import UIKit
#endif
-import os
+import Synchronization
import RSCore
extension RSImage {
@@ -24,7 +24,8 @@ public final class IconImage: @unchecked Sendable {
public let isBackgroundSuppressed: Bool
public let preferredColor: RSColor?
- private let cachedLuminanceType = OSAllocatedUnfairLock(initialState: nil)
+ private let cachedLuminanceType: Mutex
+ private let cachedGrayscaleIconImage: Mutex
private static let luminanceQueue = DispatchQueue(label: "com.ranchero.NetNewsWire.IconImage.luminance", qos: .utility, attributes: .concurrent)
public var isDark: Bool {
@@ -35,15 +36,50 @@ public final class IconImage: @unchecked Sendable {
luminanceType == .bright
}
+ /// This icon without color: bitmaps converted to grayscale, symbols tinted gray.
+ public var grayscaleIconImage: IconImage {
+ if let grayscaleIconImage = cachedGrayscaleIconImage.withLock({ $0 }) {
+ return grayscaleIconImage
+ }
+ let grayscaleIconImage = makeGrayscaleIconImage()
+ return cachedGrayscaleIconImage.withLock {
+ if let existingIconImage = $0 {
+ return existingIconImage
+ }
+ $0 = grayscaleIconImage
+ return grayscaleIconImage
+ }
+ }
+
public init(_ image: RSImage, isSymbol: Bool = false, isBackgroundSuppressed: Bool = false, preferredColor: RSColor? = nil) {
self.image = image
self.isSymbol = isSymbol
self.preferredColor = preferredColor
self.isBackgroundSuppressed = isBackgroundSuppressed
+ self.cachedLuminanceType = Mutex(nil)
+ self.cachedGrayscaleIconImage = 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)
+ self.cachedGrayscaleIconImage = Mutex(nil)
+ }
+
+ /// 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 +89,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 +104,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 +115,67 @@ private extension IconImage {
}
}
- func luminanceCGImage() -> CGImage? {
+ func makeGrayscaleIconImage() -> IconImage {
+ if isSymbol {
+ return IconImage(image, isSymbol: true, isBackgroundSuppressed: isBackgroundSuppressed, preferredColor: IconImage.grayscaleSymbolColor)
+ }
+ guard let cgImage = IconImage.cgImage(of: image), let grayscaleCGImage = IconImage.grayscaleCGImage(cgImage) else {
+ return self
+ }
+ #if os(macOS)
+ let grayscaleImage = NSImage(cgImage: grayscaleCGImage, size: image.size)
+ #else
+ let grayscaleImage = UIImage(cgImage: grayscaleCGImage, scale: image.scale, orientation: image.imageOrientation)
+ #endif
+ return IconImage(grayscaleImage, isBackgroundSuppressed: isBackgroundSuppressed)
+ }
+
+ /// Draws into an RGBA buffer and sets each pixel’s red, green, and blue to its luminance, keeping alpha.
+ static func grayscaleCGImage(_ cgImage: CGImage) -> CGImage? {
+ let width = cgImage.width
+ let height = cgImage.height
+ guard width > 0, height > 0, let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else {
+ return nil
+ }
+ let bytesPerPixel = 4
+ let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
+ guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * bytesPerPixel, space: colorSpace, bitmapInfo: bitmapInfo) else {
+ return nil
+ }
+ context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
+ guard let data = context.data else {
+ return nil
+ }
+
+ // Rec. 709 luma weights. Premultiplied channels stay valid because the weights sum to 1.
+ let redWeight = 0.2126
+ let greenWeight = 0.7152
+ let blueWeight = 0.0722
+
+ let pixels = data.bindMemory(to: UInt8.self, capacity: context.bytesPerRow * height)
+ for y in 0.. CGImage? {
#if os(macOS)
image.cgImage(forProposedRect: nil, context: nil, hints: nil)
#else
diff --git a/Modules/Images/Sources/Images/IconImageDownloader.swift b/Modules/Images/Sources/Images/IconImageDownloader.swift
new file mode 100644
index 000000000..9a8043311
--- /dev/null
+++ b/Modules/Images/Sources/Images/IconImageDownloader.swift
@@ -0,0 +1,185 @@
+//
+// IconImageDownloader.swift
+// Images
+//
+// Created by Brent Simmons on 11/25/17.
+// Copyright © 2017 Ranchero Software. All rights reserved.
+//
+
+import Foundation
+import os
+import RSCore
+import RSWeb
+import ActivityLog
+
+extension Notification.Name {
+ /// userInfo key: `IconImageDownloader.urlKey`.
+ public static let iconImageDidBecomeAvailable = Notification.Name("IconImageDidBecomeAvailable")
+ /// userInfo keys: `IconImageDownloader.urlKey` and `IconImageDownloader.errorKey` (`ImageDownloadError`).
+ public static let iconImageDownloadDidFail = Notification.Name("IconImageDownloadDidFail")
+}
+
+/// What one icon source has: an icon, an icon still loading, or none.
+public enum IconLookup {
+ case found(IconImage)
+ /// The next source isn’t tried yet.
+ case loading
+ /// The next source is tried.
+ case unavailable
+
+ public var iconImage: IconImage? {
+ if case .found(let iconImage) = self {
+ return iconImage
+ }
+ return nil
+ }
+}
+
+/// Makes feed icons, favicons, and avatars from `DownloadedImageCache`’s copy, and caches them in memory by URL.
+/// Callers that share an icon URL share one load and one bitmap.
+@MainActor public final class IconImageDownloader {
+
+ public static let shared = IconImageDownloader()
+ public static let urlKey = "url"
+ public static let errorKey = "error"
+
+ nonisolated static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "IconImageDownloader")
+
+ private var iconImages = [String: IconImage]() // url: icon image
+ private var urlsInProgress = Set()
+ private var requestsToRetry = [String: Request]() // url: request that failed transiently
+
+ private init() {
+ NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleDownloadedImageDidChange(_:)), name: .downloadedImageDidChange, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(handleNetworkStatusDidChange(_:)), name: .networkStatusDidChange, object: nil)
+ }
+
+ /// Starts loading when the icon isn’t in memory. Posts `.iconImageDidBecomeAvailable` or `.iconImageDownloadDidFail` when done.
+ /// Unavailable when the URL isn’t http(s), recently failed, or is waiting to retry after a transient failure.
+ /// Activity log fires only when the request reaches the network.
+ public func iconImage(for url: String, activityOwner: ActivityOwner, activityKind: ActivityKind, activityDetail: String?) -> IconLookup {
+ guard url.hasPrefix("http://") || url.hasPrefix("https://") else {
+ Self.logger.debug("Skipping non-http(s) URL: \(url)")
+ return .unavailable
+ }
+ if let iconImage = iconImages[url] {
+ DownloadedImageCache.shared.imageWasUsed(url, checksForUpdates: true)
+ return .found(iconImage)
+ }
+ if urlsInProgress.contains(url) {
+ return .loading
+ }
+ if ImageDatabase.shared.recentlyFailed(url: url) {
+ return .unavailable
+ }
+ let request = Request(url: url, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail)
+ if DownloadedImageCache.shared.isWaitingToRetry(url) {
+ requestsToRetry[url] = request
+ return .unavailable
+ }
+
+ findIconImage(request)
+ return .loading
+ }
+
+ // MARK: - Notifications
+
+ @objc func handleAppDidGoToBackground(_ notification: Notification) {
+ iconImages.removeAll()
+ }
+
+ @objc func handleLowMemory(_ notification: Notification) {
+ iconImages.removeAll()
+ }
+
+ /// Made again even when not in memory, since icons made from the old copy may be cached elsewhere.
+ /// The old icon stays in memory until the new one replaces it.
+ @objc func handleDownloadedImageDidChange(_ notification: Notification) {
+ guard let url = notification.userInfo?[DownloadedImageCache.urlKey] as? String else {
+ return
+ }
+ findIconImage(Request(url: url, activityOwner: nil, activityKind: nil, activityDetail: nil))
+ }
+
+ /// Waits for transient failures may have just ended, so those icons are requested again.
+ /// Runs after `DownloadedImageCache` ends those waits, which it does on this notification too.
+ @objc func handleNetworkStatusDidChange(_ notification: Notification) {
+ guard NetworkMonitor.shared.isConnected else {
+ return
+ }
+ Task { @MainActor in
+ for request in requestsToRetry.values where !DownloadedImageCache.shared.isWaitingToRetry(request.url) {
+ findIconImage(request)
+ }
+ }
+ }
+}
+
+private extension IconImageDownloader {
+
+ struct Request {
+ let url: String
+ let activityOwner: ActivityOwner?
+ let activityKind: ActivityKind?
+ let activityDetail: String?
+ }
+
+ func findIconImage(_ request: Request) {
+ let url = request.url
+ guard !urlsInProgress.contains(url) else {
+ return
+ }
+ urlsInProgress.insert(url)
+ requestsToRetry[url] = nil
+
+ Task { @MainActor in
+ defer {
+ urlsInProgress.remove(url)
+ }
+ if let iconImage = await iconImageFromScaledCopy(url) {
+ cacheIconImage(iconImage, url: url)
+ return
+ }
+
+ do throws(ImageDownloadError) {
+ let storedData = try await DownloadedImageCache.shared.imageData(for: url, usesDownloadQueue: false, checksForUpdates: true, activityOwner: request.activityOwner, activityKind: request.activityKind, activityDetail: request.activityDetail)
+ let scaledData = await DownloadedImageCache.scaledIcon(from: storedData)
+ // DownloadedImageCache records download failures, but can’t know whether the data decodes as an icon.
+ guard let iconImage = await IconImage.decodedIconImage(scaledData) else {
+ ImageDatabase.shared.recordFailure(url: url)
+ postIconImageDownloadDidFail(url, error: ImageDownloadError(statusCode: nil, decodingFailed: true, isTransient: false))
+ return
+ }
+ // An image that’s already small enough needs no second file.
+ if scaledData != storedData {
+ await DownloadedImageCache.shared.saveScaledIconData(scaledData, for: url)
+ }
+ cacheIconImage(iconImage, url: url)
+ } catch {
+ if error.isTransient {
+ requestsToRetry[url] = request
+ }
+ postIconImageDownloadDidFail(url, error: error)
+ }
+ }
+ }
+
+ func iconImageFromScaledCopy(_ url: String) async -> IconImage? {
+ guard let scaledData = await DownloadedImageCache.shared.scaledIconData(for: url), let iconImage = await IconImage.decodedIconImage(scaledData) else {
+ return nil
+ }
+ DownloadedImageCache.shared.imageWasUsed(url, checksForUpdates: true)
+ return iconImage
+ }
+
+ func cacheIconImage(_ iconImage: IconImage, url: String) {
+ iconImages[url] = iconImage
+ NotificationCenter.default.post(name: .iconImageDidBecomeAvailable, object: self, userInfo: [Self.urlKey: url])
+ }
+
+ func postIconImageDownloadDidFail(_ url: String, error: ImageDownloadError) {
+ NotificationCenter.default.post(name: .iconImageDownloadDidFail, object: self, userInfo: [Self.urlKey: url, Self.errorKey: error])
+ }
+}
diff --git a/Modules/Images/Sources/Images/ImageDatabase.swift b/Modules/Images/Sources/Images/ImageDatabase.swift
new file mode 100644
index 000000000..d1f64282d
--- /dev/null
+++ b/Modules/Images/Sources/Images/ImageDatabase.swift
@@ -0,0 +1,309 @@
+//
+// ImageDatabase.swift
+// Images
+//
+// Created by Brent Simmons on 5/28/26.
+//
+
+import Foundation
+import os
+import RSCore
+import RSDatabase
+import RSDatabaseObjC
+import RSParser
+import RSWeb
+
+/// Per-URL image metadata: discovered URLs, failure tracking, and the copies `DownloadedImageCache` stores.
+@MainActor public final class ImageDatabase {
+
+ public static let shared = ImageDatabase()
+
+ private static let failureRetryDays = 5
+
+ public let databasePath: String
+
+ nonisolated static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ImageDatabase")
+
+ private let queue: DatabaseQueue
+
+ private var homePageToFaviconURL = [String: String]()
+ private var noFaviconDates = [String: Date]() // homePageURL: when no favicon was found
+ private var homePageToIconURL = [String: String]()
+ private var noIconDates = [String: Date]() // homePageURL: when no icon was found
+ private var failureDates = [String: Date]()
+ private var urlsUnsuitableForThumbnails = Set()
+
+ private static let tableCreationStatements = """
+ CREATE TABLE IF NOT EXISTS downloadFailure (url TEXT PRIMARY KEY NOT NULL, lastChecked REAL NOT NULL);
+ CREATE TABLE IF NOT EXISTS homePageFavicon (homePageURL TEXT PRIMARY KEY NOT NULL, faviconURL TEXT, lastChecked REAL NOT NULL);
+ CREATE TABLE IF NOT EXISTS homePageIcon (homePageURL TEXT PRIMARY KEY NOT NULL, iconURL TEXT, lastChecked REAL NOT NULL);
+ CREATE TABLE IF NOT EXISTS downloadedImage (url TEXT PRIMARY KEY NOT NULL, pixelWidth INTEGER, pixelHeight INTEGER, lastAccessed REAL NOT NULL, etag TEXT, lastModified TEXT, nextCheck REAL NOT NULL, isIcon INTEGER NOT NULL DEFAULT 0);
+ """
+
+ private static let databaseFileName = "Images.db"
+ private static let legacyDatabaseFileName = "ImageMetadata.db"
+
+ /// Tables and columns imported from ImageMetadata.db, which shipped before Images.db replaced it.
+ nonisolated private static let legacyTableColumns = [
+ (table: "downloadFailure", columns: "url, lastChecked"),
+ (table: "homePageFavicon", columns: "homePageURL, faviconURL, lastChecked")
+ ]
+
+ private convenience init() {
+ self.init(databasePath: AppConfig.dataFolder.appendingPathComponent(Self.databaseFileName).path, legacyDatabasePath: AppConfig.dataFolder.appendingPathComponent(Self.legacyDatabaseFileName).path)
+ }
+
+ init(databasePath: String, legacyDatabasePath: String? = nil) {
+ self.databasePath = databasePath
+ let queue = DatabaseQueue(databasePath: databasePath, journalMode: .wal)
+ queue.runCreateStatements(Self.tableCreationStatements)
+ self.queue = queue
+
+ if let legacyDatabasePath, FileManager.default.fileExists(atPath: legacyDatabasePath) {
+ queue.runInDatabaseSync { database in
+ Self.importLegacyDatabase(path: legacyDatabasePath, database: database)
+ }
+ // Deleted even if the import failed: the data can be rebuilt, and this keeps the import to one run.
+ Self.deleteLegacyDatabase(path: legacyDatabasePath)
+ }
+
+ loadCachesFromDatabase()
+
+ let failureCutoff = Date().timeIntervalSince1970 - TimeInterval(days: Self.failureRetryDays)
+ queue.runInDatabase { database in
+ // Replaced by homePageIcon. Its home page icon URLs are found again from the home pages’ metadata.
+ database.executeStatements("DROP TABLE IF EXISTS feedIconURL;")
+ DownloadFailureTable.removeExpired(olderThan: failureCutoff, database: database)
+ database.checkpoint()
+ }
+ }
+
+ // MARK: - Vacuum
+
+ /// A WAL checkpoint, since this database is in WAL mode.
+ public func vacuum() async {
+ await queue.checkpoint()
+ }
+
+ // MARK: - HomePageFavicon
+
+ public func faviconURL(forHomePageURL homePageURL: String) -> String? {
+ homePageToFaviconURL[homePageURL]
+ }
+
+ public func homePageURLs(withFaviconURL faviconURL: String) -> [String] {
+ homePageToFaviconURL.filter { $0.value == faviconURL }.map { $0.key }
+ }
+
+ /// A no-favicon verdict expires after `failureRetryDays`, so the home page gets checked again.
+ public func homePageHasNoFavicon(_ homePageURL: String) -> Bool {
+ guard let noFaviconDate = noFaviconDates[homePageURL] else {
+ return false
+ }
+ return Date().timeIntervalSince(noFaviconDate) < TimeInterval(days: Self.failureRetryDays)
+ }
+
+ public func saveHomePageFavicon(homePageURL: String, faviconURL: String?) {
+ if let faviconURL {
+ homePageToFaviconURL[homePageURL] = faviconURL
+ noFaviconDates.removeValue(forKey: homePageURL)
+ } else {
+ noFaviconDates[homePageURL] = Date()
+ homePageToFaviconURL.removeValue(forKey: homePageURL)
+ }
+ queue.runInDatabase { database in
+ HomePageFaviconTable.save(homePageURL: homePageURL, faviconURL: faviconURL, database: database)
+ }
+ }
+
+ // MARK: - HomePageIcon
+
+ public func homePageIconURL(forHomePageURL homePageURL: String) -> String? {
+ homePageToIconURL[homePageURL]
+ }
+
+ /// A no-icon verdict expires after `failureRetryDays`, so the home page gets checked again.
+ public func homePageHasNoIcon(_ homePageURL: String) -> Bool {
+ guard let noIconDate = noIconDates[homePageURL] else {
+ return false
+ }
+ return Date().timeIntervalSince(noIconDate) < TimeInterval(days: Self.failureRetryDays)
+ }
+
+ public func saveHomePageIcon(homePageURL: String, iconURL: String?) {
+ if let iconURL {
+ homePageToIconURL[homePageURL] = iconURL
+ noIconDates.removeValue(forKey: homePageURL)
+ } else {
+ noIconDates[homePageURL] = Date()
+ homePageToIconURL.removeValue(forKey: homePageURL)
+ }
+ queue.runInDatabase { database in
+ HomePageIconTable.save(homePageURL: homePageURL, iconURL: iconURL, database: database)
+ }
+ }
+
+ // MARK: - DownloadFailure
+
+ public func recentlyFailed(url: String) -> Bool {
+ guard let lastFailure = failureDates[url] else {
+ return false
+ }
+ return Date().timeIntervalSince(lastFailure) < TimeInterval(days: Self.failureRetryDays)
+ }
+
+ public func recordFailure(url: String) {
+ failureDates[url] = Date()
+ queue.runInDatabase { database in
+ DownloadFailureTable.save(url: url, database: database)
+ }
+ }
+
+ public func clearFailure(url: String) {
+ guard failureDates.removeValue(forKey: url) != nil else {
+ return
+ }
+ queue.runInDatabase { database in
+ DownloadFailureTable.clear(url: url, database: database)
+ }
+ }
+
+ // MARK: - DownloadedImage
+
+ /// True when the image is too large to download for the timeline, or the stored copy is too small, too narrow, or unreadable by ImageIO.
+ /// It may still be a fine feed icon.
+ public func isUnsuitableForThumbnail(url: String) -> Bool {
+ urlsUnsuitableForThumbnails.contains(url)
+ }
+
+ /// For this session.
+ func saveUnsuitableForThumbnail(url: String) {
+ urlsUnsuitableForThumbnails.insert(url)
+ }
+
+ func saveDownloadedImage(_ record: DownloadedImageRecord) {
+ if Self.isSuitableForThumbnail(record.pixelSize) {
+ urlsUnsuitableForThumbnails.remove(record.url)
+ } else {
+ urlsUnsuitableForThumbnails.insert(record.url)
+ }
+ queue.runInDatabase { database in
+ DownloadedImageTable.save(record, database: database)
+ }
+ }
+
+ func saveDownloadedImageAccessDate(url: String) {
+ queue.runInDatabase { database in
+ DownloadedImageTable.saveAccessDate(url: url, database: database)
+ }
+ }
+
+ func saveDownloadedImageIsIcon(url: String) {
+ queue.runInDatabase { database in
+ DownloadedImageTable.saveIsIcon(url: url, database: database)
+ }
+ }
+
+ func fetchDownloadedImageValidation(url: String) async -> DownloadedImageValidation? {
+ await withCheckedContinuation { continuation in
+ queue.runInDatabase { database in
+ continuation.resume(returning: DownloadedImageTable.fetchValidation(url: url, database: database))
+ }
+ }
+ }
+
+ /// Saves `conditionalGetInfo` too when it’s not nil. Otherwise the saved validators are kept.
+ func saveDownloadedImageNextCheck(url: String, nextCheck: Date, conditionalGetInfo: HTTPConditionalGetInfo?) {
+ queue.runInDatabase { database in
+ DownloadedImageTable.saveNextCheck(url: url, nextCheck: nextCheck, conditionalGetInfo: conditionalGetInfo, database: database)
+ }
+ }
+
+ func fetchDownloadedImageUsageByLeastRecentAccess() async -> [DownloadedImageUsage]? {
+ await withCheckedContinuation { continuation in
+ queue.runInDatabase { database in
+ continuation.resume(returning: DownloadedImageTable.fetchUsageByLeastRecentAccess(database: database))
+ }
+ }
+ }
+
+ func deleteDownloadedImages(urls: [String]) {
+ guard !urls.isEmpty else {
+ return
+ }
+ urlsUnsuitableForThumbnails.subtract(urls)
+ queue.runInTransaction { database in
+ DownloadedImageTable.delete(urls: urls, database: database)
+ }
+ }
+}
+
+private extension ImageDatabase {
+
+ static func isSuitableForThumbnail(_ pixelSize: (width: Int, height: Int)?) -> Bool {
+ guard let pixelSize else {
+ return false
+ }
+ return SignificantImageFilter.hasSignificantDimensions(width: pixelSize.width, height: pixelSize.height)
+ }
+
+ nonisolated static func importLegacyDatabase(path: String, database: FMDatabase) {
+ guard database.executeUpdate("ATTACH DATABASE ? AS legacy", withArgumentsIn: [path]) else {
+ logger.error("Could not attach legacy database: \(database.lastErrorMessage() ?? "unknown", privacy: .public)")
+ return
+ }
+
+ // ATTACH and DETACH can’t run inside a transaction.
+ database.beginTransaction()
+ for (table, columns) in legacyTableColumns {
+ if database.executeUpdate("INSERT OR IGNORE INTO main.\(table) (\(columns)) SELECT \(columns) FROM legacy.\(table)", withArgumentsIn: []) {
+ let rowCount = database.changes()
+ logger.info("Imported \(rowCount) rows into \(table, privacy: .public) from legacy database")
+ } else {
+ logger.error("Could not import \(table, privacy: .public) from legacy database: \(database.lastErrorMessage() ?? "unknown", privacy: .public)")
+ }
+ }
+ database.commit()
+
+ database.executeStatements("DETACH DATABASE legacy;")
+ }
+
+ static func deleteLegacyDatabase(path: String) {
+ do {
+ try FileManager.default.removeItem(atPath: path)
+ } catch {
+ logger.error("Could not delete legacy database \(path, privacy: .public): \(error.localizedDescription, privacy: .public)")
+ }
+ }
+
+ func loadCachesFromDatabase() {
+ nonisolated(unsafe) var homePageRecords = [HomePageFaviconRecord]()
+ nonisolated(unsafe) var homePageIconRecords = [HomePageIconRecord]()
+ nonisolated(unsafe) var failures = [String: Date]()
+ nonisolated(unsafe) var pixelSizes = [(url: String, pixelSize: (width: Int, height: Int)?)]()
+
+ queue.runInDatabaseSync { database in
+ homePageRecords = HomePageFaviconTable.fetchAll(database: database)
+ homePageIconRecords = HomePageIconTable.fetchAll(database: database)
+ failures = DownloadFailureTable.fetchAll(database: database)
+ pixelSizes = DownloadedImageTable.fetchPixelSizes(database: database)
+ }
+
+ for record in homePageRecords {
+ if let faviconURL = record.faviconURL {
+ homePageToFaviconURL[record.homePageURL] = faviconURL
+ } else {
+ noFaviconDates[record.homePageURL] = record.lastChecked
+ }
+ }
+ for record in homePageIconRecords {
+ if let iconURL = record.iconURL {
+ homePageToIconURL[record.homePageURL] = iconURL
+ } else {
+ noIconDates[record.homePageURL] = record.lastChecked
+ }
+ }
+ failureDates = failures
+ urlsUnsuitableForThumbnails = Set(pixelSizes.filter { !Self.isSuitableForThumbnail($0.pixelSize) }.map(\.url))
+ }
+}
diff --git a/Modules/Images/Sources/Images/ImageDownloadError.swift b/Modules/Images/Sources/Images/ImageDownloadError.swift
new file mode 100644
index 000000000..1b31a782d
--- /dev/null
+++ b/Modules/Images/Sources/Images/ImageDownloadError.swift
@@ -0,0 +1,50 @@
+//
+// ImageDownloadError.swift
+// Images
+//
+// Created by Brent Simmons on 11/3/26.
+//
+
+import Foundation
+
+public struct ImageDownloadError: Error {
+ public let statusCode: Int?
+ public let decodingFailed: Bool
+ public let isTransient: Bool // No network, DNS issues, timeout, 5xx, 429, or 408 response, etc.
+ public let rejectedPixelSize: (width: Int, height: Int)? // Too small or too narrow to be a thumbnail
+ public let retryAfter: TimeInterval? // From a Retry-After header in seconds
+ public let rejectedByteCount: Int? // Too large to save for the timeline
+
+ /// No request was made: waiting to retry, dropped from the download queue, or the network doesn’t allow the download.
+ static let notAttempted = ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true)
+
+ init(statusCode: Int?, decodingFailed: Bool, isTransient: Bool, rejectedPixelSize: (width: Int, height: Int)? = nil, retryAfter: TimeInterval? = nil, rejectedByteCount: Int? = nil) {
+ self.statusCode = statusCode
+ self.decodingFailed = decodingFailed
+ self.isTransient = isTransient
+ self.rejectedPixelSize = rejectedPixelSize
+ self.retryAfter = retryAfter
+ self.rejectedByteCount = rejectedByteCount
+ }
+}
+
+extension ImageDownloadError: LocalizedError {
+ public var errorDescription: String? {
+ if let rejectedByteCount {
+ return "Image too large (\(rejectedByteCount) bytes)"
+ }
+ if let rejectedPixelSize {
+ return "Image too small or too narrow (\(rejectedPixelSize.width)×\(rejectedPixelSize.height))"
+ }
+ if decodingFailed {
+ if let statusCode {
+ return "Couldn’t decode image bytes (HTTP \(statusCode))"
+ }
+ return "Couldn’t decode image bytes"
+ }
+ guard let statusCode else {
+ return isTransient ? "No response" : "Bad URL"
+ }
+ return "HTTP \(statusCode)"
+ }
+}
diff --git a/Modules/Images/Sources/Images/ImageDownloader.swift b/Modules/Images/Sources/Images/ImageDownloader.swift
deleted file mode 100644
index 1b1d17a44..000000000
--- a/Modules/Images/Sources/Images/ImageDownloader.swift
+++ /dev/null
@@ -1,202 +0,0 @@
-//
-// ImageDownloader.swift
-// Images
-//
-// Created by Brent Simmons on 11/25/17.
-// Copyright © 2017 Ranchero Software. All rights reserved.
-//
-
-import Foundation
-import os
-import RSCore
-import RSWeb
-import ActivityLog
-
-extension Notification.Name {
- public static let imageDidBecomeAvailable = Notification.Name("ImageDidBecomeAvailableNotification") // userInfo key: "url"
-}
-
-public struct ImageDownloadError: Error {
- public let statusCode: Int?
- public let decodingFailed: Bool
- public let isTransient: Bool // No network, DNS issues, timeout, 5xx response, etc.
-}
-
-extension ImageDownloadError: LocalizedError {
- public var errorDescription: String? {
- if decodingFailed {
- if let statusCode {
- return "Couldn’t decode image bytes (HTTP \(statusCode))"
- }
- return "Couldn’t decode image bytes"
- }
- guard let statusCode else {
- return isTransient ? "No response" : "Bad URL"
- }
- return "HTTP \(statusCode)"
- }
-}
-
-@MainActor public final class ImageDownloader {
- public static let shared = ImageDownloader()
-
- nonisolated static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ImageDownloader")
-
- nonisolated private let diskCache: BinaryDiskCache
- private let queue: DispatchQueue
- private var imageCache = [String: Data]() // url: image
- private var urlsInProgress = Set()
-
- init() {
- let folder = AppConfig.cacheSubfolder(named: "Images")
- self.diskCache = BinaryDiskCache(folder: folder.path)
- self.queue = DispatchQueue(label: "ImageDownloader serial queue - \(folder.path)")
-
- NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
- }
-
- @objc func handleAppDidGoToBackground(_ notification: Notification) {
- imageCache.removeAll()
- }
-
- @objc func handleLowMemory(_ notification: Notification) {
- imageCache.removeAll()
- }
-
- /// Returns the data if in memory, else dispatches a disk-then-network fetch and returns nil.
- /// Activity log fires only when the fetch reaches the network.
- @discardableResult
- public func image(for url: String, activityOwner: ActivityOwner? = nil, activityKind: ActivityKind? = nil, activityDetail: String? = nil) -> Data? {
- assert(Thread.isMainThread)
- if !url.hasPrefix("http://") && !url.hasPrefix("https://") {
- Self.logger.debug("Skipping non-http(s) URL: \(url)")
- return nil
- }
- if let data = imageCache[url] {
- return data
- }
- if ImageMetadataDatabase.shared.recentlyFailed(url: url) {
- Self.logger.debug("Skipping recently-failed URL: \(url)")
- return nil
- }
-
- Task { @MainActor in
- await findImage(url, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail)
- }
-
- return nil
- }
-}
-
-private extension ImageDownloader {
-
- func cacheImage(_ url: String, _ image: Data) {
- assert(Thread.isMainThread)
- imageCache[url] = image
- postImageDidBecomeAvailableNotification(url)
- }
-
- func findImage(_ url: String, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async {
- guard !urlsInProgress.contains(url) else {
- return
- }
- urlsInProgress.insert(url)
-
- if let image = await readFromDisk(url: url) {
- cacheImage(url, image)
- urlsInProgress.remove(url)
- return
- }
-
- let activityLog = ActivityLog.shared
- if let activityOwner, let activityKind {
- activityLog.createActivity(owner: activityOwner, kind: activityKind, detail: activityDetail)
- activityLog.didStart(activityOwner, kind: activityKind)
- }
-
- do {
- let (image, downloadResponse) = try await downloadImage(url)
- if let activityOwner, let activityKind {
- let message = downloadResponse.data.map(ActivityLog.dataSizeMessage)
- activityLog.didComplete(activityOwner, kind: activityKind, message: message, returnedFromCache: downloadResponse.returnedFromCache)
- }
- cacheImage(url, image)
- ImageMetadataDatabase.shared.clearFailure(url: url)
- } catch {
- if let activityOwner, let activityKind {
- activityLog.didFail(activityOwner, kind: activityKind, error: error)
- }
- if !error.isTransient {
- ImageMetadataDatabase.shared.recordFailure(url: url, statusCode: error.statusCode)
- }
- }
- 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 @MainActor (Data?) -> Void) {
- queue.async {
- if let data = self.diskCache[self.diskKey(url)], !data.isEmpty {
- DispatchQueue.main.async {
- completion(data)
- }
- return
- }
-
- DispatchQueue.main.async {
- completion(nil)
- }
- }
- }
-
- func downloadImage(_ url: String) async throws(ImageDownloadError) -> (Data, DownloadResponse) {
- guard let imageURL = URL(string: url) else {
- throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: false)
- }
-
- let downloadResponse: DownloadResponse
- do {
- downloadResponse = try await Downloader.shared.download(imageURL, userAgentStyle: .browser)
- } catch {
- Self.logger.error("Error downloading image at \(url) \(error.localizedDescription)")
- throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true)
- }
-
- if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK {
- let scaledData = RSImage.scaledImageData(data, maxPixelSize: RSImage.maxIconPixelSize) ?? data
- saveToDisk(url, scaledData)
- return (scaledData, downloadResponse)
- }
-
- let statusCode = (downloadResponse.response as? HTTPURLResponse)?.statusCode
- // 2xx with empty / missing body — server said OK but gave us no image bytes.
- if let response = downloadResponse.response, response.statusIsOK {
- throw ImageDownloadError(statusCode: statusCode, decodingFailed: true, isTransient: false)
- }
- let isTransient = statusCode.map { (500...599).contains($0) } ?? true
- throw ImageDownloadError(statusCode: statusCode, decodingFailed: false, isTransient: isTransient)
- }
-
- func saveToDisk(_ url: String, _ data: Data) {
- queue.async {
- self.diskCache[self.diskKey(url)] = data
- }
- }
-
- nonisolated func diskKey(_ url: String) -> String {
- url.md5String
- }
-
- func postImageDidBecomeAvailableNotification(_ url: String) {
- assert(Thread.isMainThread)
- NotificationCenter.default.post(name: .imageDidBecomeAvailable, object: self, userInfo: ["url": url])
- }
-}
diff --git a/Modules/Images/Sources/Images/ImageMetadataDatabase.swift b/Modules/Images/Sources/Images/ImageMetadataDatabase.swift
deleted file mode 100644
index e9751a82f..000000000
--- a/Modules/Images/Sources/Images/ImageMetadataDatabase.swift
+++ /dev/null
@@ -1,163 +0,0 @@
-//
-// ImageMetadataDatabase.swift
-// Images
-//
-// Created by Brent Simmons on 5/28/26.
-//
-
-import Foundation
-import os
-import RSCore
-import RSDatabase
-import RSDatabaseObjC
-
-/// Per-URL image metadata: discovered URLs and failure tracking.
-@MainActor public final class ImageMetadataDatabase {
-
- public static let shared = ImageMetadataDatabase()
-
- public static let failureRetryDays = 5
- private static let failureRetentionDays = 33
-
- public let databasePath: String
-
- nonisolated static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ImageMetadataDatabase")
-
- private let queue: DatabaseQueue
-
- private var homePageToFaviconURL = [String: String]()
- private var homePagesWithNoFavicon = Set()
- private var feedURLToIconURL = [String: String]()
- private var failureDates = [String: Date]()
-
- private static let tableCreationStatements = """
- CREATE TABLE IF NOT EXISTS downloadFailure (url TEXT PRIMARY KEY NOT NULL, statusCode INTEGER, lastChecked REAL NOT NULL);
- CREATE TABLE IF NOT EXISTS homePageFavicon (homePageURL TEXT PRIMARY KEY NOT NULL, faviconURL TEXT, lastChecked REAL NOT NULL);
- CREATE TABLE IF NOT EXISTS feedIconURL (feedURL TEXT PRIMARY KEY NOT NULL, iconURL TEXT NOT NULL, lastChecked REAL NOT NULL);
- """
-
- private init() {
- let databasePath = AppConfig.dataFolder
- .appendingPathComponent("ImageMetadata.db").path
- self.databasePath = databasePath
- let queue = DatabaseQueue(databasePath: databasePath)
- queue.runCreateStatements(Self.tableCreationStatements)
- self.queue = queue
-
- loadCachesFromDatabase()
-
- let cutoff = Date().timeIntervalSince1970 - TimeInterval(days: Self.failureRetentionDays)
- queue.runInDatabase { database in
- DownloadFailureTable.removeExpired(olderThan: cutoff, database: database)
- database.vacuumIfNeeded()
- }
- }
-
- // MARK: - Vacuum
-
- public func vacuum() async {
- await queue.vacuum()
- }
-
- // MARK: - HomePageFavicon
-
- public func faviconURL(forHomePageURL homePageURL: String) -> String? {
- homePageToFaviconURL[homePageURL]
- }
-
- public func homePageHasNoFavicon(_ homePageURL: String) -> Bool {
- homePagesWithNoFavicon.contains(homePageURL)
- }
-
- public func saveHomePageFavicon(homePageURL: String, faviconURL: String?) {
- if let faviconURL {
- homePageToFaviconURL[homePageURL] = faviconURL
- homePagesWithNoFavicon.remove(homePageURL)
- } else {
- homePagesWithNoFavicon.insert(homePageURL)
- homePageToFaviconURL.removeValue(forKey: homePageURL)
- }
- queue.runInDatabase { database in
- HomePageFaviconTable.save(homePageURL: homePageURL, faviconURL: faviconURL, database: database)
- }
- }
-
- // MARK: - FeedIconURL
-
- public func iconURL(forFeedURL feedURL: String) -> String? {
- feedURLToIconURL[feedURL]
- }
-
- public func saveFeedIconURL(feedURL: String, iconURL: String) {
- feedURLToIconURL[feedURL] = iconURL
- queue.runInDatabase { database in
- FeedIconURLTable.save(feedURL: feedURL, iconURL: iconURL, database: database)
- }
- }
-
- // MARK: - DownloadFailure
-
- public func recentlyFailed(url: String) -> Bool {
- guard let lastFailure = failureDates[url] else {
- return false
- }
- return Date().timeIntervalSince(lastFailure) < TimeInterval(days: Self.failureRetryDays)
- }
-
- public func recordFailure(url: String, statusCode: Int?) {
- failureDates[url] = Date()
- queue.runInDatabase { database in
- DownloadFailureTable.save(url: url, statusCode: statusCode, database: database)
- }
- }
-
- public func clearFailure(url: String) {
- guard failureDates.removeValue(forKey: url) != nil else {
- return
- }
- queue.runInDatabase { database in
- DownloadFailureTable.clear(url: url, database: database)
- }
- }
-}
-
-private extension ImageMetadataDatabase {
-
- func loadCachesFromDatabase() {
- nonisolated(unsafe) var homePageRecords = [HomePageFaviconRecord]()
- nonisolated(unsafe) var feedIcons = [String: String]()
- nonisolated(unsafe) var failures = [String: Date]()
- nonisolated(unsafe) var homePageDuration: TimeInterval = 0
- nonisolated(unsafe) var feedIconDuration: TimeInterval = 0
- nonisolated(unsafe) var failureDuration: TimeInterval = 0
-
- let totalStart = Date()
- queue.runInDatabaseSync { database in
- var stepStart = Date()
- homePageRecords = HomePageFaviconTable.fetchAll(database: database)
- homePageDuration = Date().timeIntervalSince(stepStart)
-
- stepStart = Date()
- feedIcons = FeedIconURLTable.fetchAll(database: database)
- feedIconDuration = Date().timeIntervalSince(stepStart)
-
- stepStart = Date()
- failures = DownloadFailureTable.fetchAll(database: database)
- failureDuration = Date().timeIntervalSince(stepStart)
- }
- let totalDuration = Date().timeIntervalSince(totalStart)
-
- for record in homePageRecords {
- if let faviconURL = record.faviconURL {
- homePageToFaviconURL[record.homePageURL] = faviconURL
- } else if Date().timeIntervalSince(record.lastChecked) < TimeInterval(days: Self.failureRetryDays) {
- // A no-favicon verdict expires after failureRetryDays, so the homepage gets rechecked.
- homePagesWithNoFavicon.insert(record.homePageURL)
- }
- }
- feedURLToIconURL = feedIcons
- failureDates = failures
-
- Self.logger.info("Initial fetches: homePageFavicon \(homePageRecords.count) rows in \(homePageDuration) seconds, feedIconURL \(feedIcons.count) rows in \(feedIconDuration) seconds, downloadFailure \(failures.count) rows in \(failureDuration) seconds, total \(totalDuration) seconds")
- }
-}
diff --git a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift
deleted file mode 100644
index 49b2ebe46..000000000
--- a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift
+++ /dev/null
@@ -1,188 +0,0 @@
-//
-// SingleFaviconDownloader.swift
-// Images
-//
-// Created by Brent Simmons on 11/23/17.
-// Copyright © 2017 Ranchero Software. All rights reserved.
-//
-
-import Foundation
-import os
-import ActivityLog
-import RSCore
-import RSWeb
-
-extension Notification.Name {
- public static let DidLoadFavicon = Notification.Name("DidLoadFaviconNotification")
-}
-
-/// Reads from disk, falls back to network. Posts `.DidLoadFavicon` on both
-/// success and persistent failure.
-@MainActor public final class SingleFaviconDownloader {
- private enum DiskStatus {
- case unknown, notOnDisk, onDisk
- }
-
- public let faviconURL: String
- public let homePageURL: String?
-
- public var iconImage: IconImage?
-
- /// The persistent failure, if any. Nil after success or for transient failures.
- public private(set) var error: ImageDownloadError?
-
- static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "SingleFaviconDownloader")
-
- private let diskCache: BinaryDiskCache
- private let queue: DispatchQueue
- private let diskKey: String
-
- private var lastDownloadAttemptDate: Date
- private var diskStatus = DiskStatus.unknown
-
- public 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
-
- Task { @MainActor in
- await findFavicon()
- }
- }
-
- public func downloadFaviconIfNeeded() -> Bool {
- // If we don’t have an image, and lastDownloadAttemptDate is a while ago, try again.
- guard iconImage == nil else {
- return false
- }
-
- let retryInterval: TimeInterval = 30 * 60 // 30 minutes
- if Date().timeIntervalSince(lastDownloadAttemptDate) < retryInterval {
- return false
- }
- lastDownloadAttemptDate = Date()
-
- Task { @MainActor in
- await findFavicon()
- }
-
- return true
- }
-}
-
-private extension SingleFaviconDownloader {
-
- func findFavicon() async {
- if let image = await readFromDisk() {
- diskStatus = .onDisk
- iconImage = IconImage(image)
- error = nil
- postDidLoadFaviconNotification()
- return
- }
-
- diskStatus = .notOnDisk
-
- do {
- let image = try await downloadFavicon()
- iconImage = IconImage(image)
- error = nil
- } catch {
- self.error = error.isTransient ? nil : error
- }
- postDidLoadFaviconNotification()
- }
-
- func readFromDisk() async -> RSImage? {
- await withCheckedContinuation { continuation in
- readFromDisk { image in
- continuation.resume(returning: image)
- }
- }
- }
-
- 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
- }
-
- Task { @MainActor in
- completion(nil)
- }
- }
- }
-
- func saveToDisk(_ data: Data) {
- queue.async {
- do {
- try self.diskCache.setData(data, forKey: self.diskKey)
- Task { @MainActor in
- self.diskStatus = .onDisk
- }
- } catch {}
- }
- }
-
- func downloadFavicon() async throws(ImageDownloadError) -> RSImage {
- assert(Thread.isMainThread)
-
- guard let url = URL(string: faviconURL) else {
- throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: false)
- }
-
- let activityLog = ActivityLog.shared
- let kind = ActivityKind.downloadFavicon(faviconURL: faviconURL)
- activityLog.createActivity(owner: .faviconDownloader, kind: kind, detail: homePageURL)
- activityLog.didStart(.faviconDownloader, kind: kind)
-
- let downloadResponse: DownloadResponse
- do {
- downloadResponse = try await Downloader.shared.download(url, userAgentStyle: .browser)
- } catch {
- Self.logger.error("Error downloading image at \(url.absoluteString): \(error.localizedDescription)")
- activityLog.didFail(.faviconDownloader, kind: kind, error: error)
- throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true)
- }
-
- if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK {
- let scaledData = RSImage.scaledImageData(data, maxPixelSize: RSImage.maxIconPixelSize) ?? data
- let image = await RSImage.image(data: scaledData)
- guard let image else {
- let responseStatusCode = (response as? HTTPURLResponse)?.statusCode
- let error = ImageDownloadError(statusCode: responseStatusCode, decodingFailed: true, isTransient: false)
- activityLog.didFail(.faviconDownloader, kind: kind, error: error)
- throw error
- }
- saveToDisk(scaledData)
- activityLog.didComplete(.faviconDownloader, kind: kind, message: ActivityLog.dataSizeMessage(data), returnedFromCache: downloadResponse.returnedFromCache)
- return image
- }
-
- let statusCode = (downloadResponse.response as? HTTPURLResponse)?.statusCode
- // 2xx with empty / missing body — server said OK but gave us no image bytes.
- if let response = downloadResponse.response, response.statusIsOK {
- let error = ImageDownloadError(statusCode: statusCode, decodingFailed: true, isTransient: false)
- activityLog.didFail(.faviconDownloader, kind: kind, error: error)
- throw error
- }
- let isTransient = statusCode.map { (500...599).contains($0) } ?? true
- let error = ImageDownloadError(statusCode: statusCode, decodingFailed: false, isTransient: isTransient)
- activityLog.didFail(.faviconDownloader, kind: kind, error: error)
- throw error
- }
-
- func postDidLoadFaviconNotification() {
- assert(Thread.isMainThread)
- NotificationCenter.default.post(name: .DidLoadFavicon, object: self)
- }
-}
diff --git a/Modules/Images/Sources/Images/SpecialCase+Icons.swift b/Modules/Images/Sources/Images/SpecialCase+Icons.swift
new file mode 100644
index 000000000..320eede74
--- /dev/null
+++ b/Modules/Images/Sources/Images/SpecialCase+Icons.swift
@@ -0,0 +1,14 @@
+//
+// SpecialCase+Icons.swift
+// Images
+//
+// Created by Brent Simmons on 11/3/26.
+//
+
+import Foundation
+import RSWeb
+
+extension SpecialCase {
+ /// Matched anywhere in the feed URL or home page URL. A match means neither the feed icon nor the home page icon is used.
+ static let hostNamesWithoutFeedOrHomePageIcons = ["macsparky.com", "xkcd.com", SpecialCase.rachelByTheBayHostName, SpecialCase.openRSSOrgHostName]
+}
diff --git a/Modules/Images/Sources/Images/ThumbnailDownloader.swift b/Modules/Images/Sources/Images/ThumbnailDownloader.swift
new file mode 100644
index 000000000..842cd5852
--- /dev/null
+++ b/Modules/Images/Sources/Images/ThumbnailDownloader.swift
@@ -0,0 +1,269 @@
+//
+// ThumbnailDownloader.swift
+// Images
+//
+// Created by Brent Simmons on 11/3/26.
+//
+
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+import ImageIO
+import RSCore
+import RSParser
+import RSWeb
+import ActivityLog
+
+extension Notification.Name {
+ /// Posted when a thumbnail image requested by `thumbnail(url:mode:articleTitle:)` is ready.
+ /// userInfo key: `ThumbnailDownloader.urlKey`.
+ public static let thumbnailDidBecomeAvailable = Notification.Name("ThumbnailDidBecomeAvailable")
+
+ /// Posted when a thumbnail image fails to download or decode, or is rejected for its size.
+ /// userInfo keys: `ThumbnailDownloader.urlKey` and `ThumbnailDownloader.errorKey` (`ImageDownloadError`).
+ public static let thumbnailDownloadDidFail = Notification.Name("ThumbnailDownloadDidFail")
+}
+
+public enum ThumbnailMode: String, Sendable, CaseIterable {
+ case small
+ case large
+}
+
+/// Downloads and decodes the timeline’s thumbnail images, and caches them in memory.
+///
+/// Images are decoded at display size from `DownloadedImageCache`’s copy, off the main thread,
+/// a few at a time and newest first, so a fast scroll doesn’t spend time on rows long gone.
+@MainActor public final class ThumbnailDownloader {
+
+ public static let shared = ThumbnailDownloader()
+
+ public static let urlKey = "url"
+ public static let errorKey = "error"
+
+ private let imageCache = NSCache() // See cacheKey
+ private let decodeQueue = ThumbnailTaskQueue(maximumRunningCount: maximumConcurrentDecodes, maximumWaitingCount: maximumWaitingDecodes)
+ private var decodeKeysInProgress = Set()
+
+ /// Decoded bitmaps: about 0.25 MB each in small mode, at most about 2.5 MB in large mode.
+ #if os(macOS)
+ private static let imageCacheByteLimit = 128 * 1024 * 1024
+ #else
+ private static let imageCacheByteLimit = 64 * 1024 * 1024
+ #endif
+ /// The small thumbnail is a square of at most 76pt, which is 228 pixels at 3x.
+ private static let smallThumbnailPixelSize = 256
+ /// The longest side of a wide image, which fills the timeline’s width before it reaches the height limit.
+ private static let largeThumbnailMaxPixelSize = 1200
+ /// The large thumbnail is aspect-fit into a box 180pt tall.
+ #if os(macOS)
+ private static let largeThumbnailMaxPixelHeight = 360
+ #else
+ private static let largeThumbnailMaxPixelHeight = 540
+ #endif
+ nonisolated private static let squareBitsPerComponent = 8
+ private static let maximumConcurrentDecodes = 4
+ /// A few screens of thumbnails.
+ private static let maximumWaitingDecodes = 60
+
+ private init() {
+ self.imageCache.totalCostLimit = Self.imageCacheByteLimit
+
+ NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
+ }
+
+ /// False when offline or in Low Data Mode, when thumbnails not already on disk aren’t downloaded.
+ public var networkAllowsDownloads: Bool {
+ DownloadedImageCache.networkAllowsDownloads
+ }
+
+ /// `url` is from `ArticleThumbnailFinder.thumbnailURL(for:mode:)`. `articleTitle` is shown in the activity log when the download fails.
+ /// Nil when the image isn’t ready. Starts a download when needed and posts
+ /// `.thumbnailDidBecomeAvailable` once the image is ready.
+ public func thumbnail(url: String, mode: ThumbnailMode, articleTitle: String?) -> RSImage? {
+ if let image = imageCache.object(forKey: Self.cacheKey(url, mode)) {
+ DownloadedImageCache.shared.imageWasUsed(url, checksForUpdates: false)
+ return image
+ }
+ findImage(url, mode: mode, activityDetail: articleTitle)
+ return nil
+ }
+
+ /// The image as downloaded, for the article view, which shows the thumbnail image at full size.
+ /// Shares the timeline’s copy and any download in progress, so the image is downloaded once.
+ /// A download starts right away rather than waiting behind timeline downloads.
+ public func fullSizeImageData(url: String, articleTitle: String?) async throws(ImageDownloadError) -> Data {
+ try await DownloadedImageCache.shared.imageData(for: url, usesDownloadQueue: false, checksForUpdates: false, activityOwner: .thumbnailDownloader, activityKind: .downloadThumbnail(imageURL: url), activityDetail: articleTitle)
+ }
+
+ // MARK: - Notifications
+
+ /// The cache is kept when the app goes to the background, since emptying it would make thumbnails flash on resume.
+ @objc func handleLowMemory(_ notification: Notification) {
+ imageCache.removeAllObjects()
+ }
+}
+
+private extension ThumbnailDownloader {
+
+ /// The same URL can be cached at both sizes.
+ static func cacheKey(_ url: String, _ mode: ThumbnailMode) -> NSString {
+ "\(mode.rawValue) \(url)" as NSString
+ }
+
+ @concurrent static func decodedImage(_ data: Data, mode: ThumbnailMode) async throws(ImageDownloadError) -> (image: RSImage, byteCount: Int) {
+ switch mode {
+ case .small:
+ try await decodedSquareImage(data, pixelSize: smallThumbnailPixelSize)
+ case .large:
+ try await decodedImage(data, maxPixelSize: largeThumbnailMaxPixelSize, maxPixelHeight: largeThumbnailMaxPixelHeight)
+ }
+ }
+
+ func findImage(_ url: String, mode: ThumbnailMode, activityDetail: String?) {
+ let cacheKey = Self.cacheKey(url, mode)
+ let decodeKey = cacheKey as String
+ guard !decodeKeysInProgress.contains(decodeKey) else {
+ DownloadedImageCache.shared.prioritizeDownload(for: url)
+ decodeQueue.prioritize(key: decodeKey)
+ return
+ }
+ decodeKeysInProgress.insert(decodeKey)
+
+ Task {
+ defer {
+ decodeKeysInProgress.remove(decodeKey)
+ }
+ do throws(ImageDownloadError) {
+ let data = try await DownloadedImageCache.shared.imageData(for: url, usesDownloadQueue: true, checksForUpdates: false, activityOwner: .thumbnailDownloader, activityKind: .downloadThumbnail(imageURL: url), activityDetail: activityDetail)
+ guard await decodeQueue.waitForTurn(key: decodeKey) != .dropped else {
+ return
+ }
+ defer {
+ decodeQueue.taskDidFinish()
+ }
+ let decodedImage = try await Self.decodedImage(data, mode: mode)
+ imageCache.setObject(decodedImage.image, forKey: cacheKey, cost: decodedImage.byteCount)
+ NotificationCenter.default.post(name: .thumbnailDidBecomeAvailable, object: self, userInfo: [Self.urlKey: url])
+ } catch {
+ NotificationCenter.default.post(name: .thumbnailDownloadDidFail, object: self, userInfo: [Self.urlKey: url, Self.errorKey: error])
+ }
+ }
+ }
+}
+
+// MARK: - Decoding
+
+extension ThumbnailDownloader {
+
+ /// Decodes now, at display size and in EXIF orientation, so drawing the image in the timeline
+ /// doesn’t decode it on the main thread. Throws when the image is unreadable, too small, or too narrow.
+ /// For a multi-image file such as ICO, the largest frame is the one checked and decoded.
+ /// With a `maxPixelHeight`, the image is also no taller than that as displayed.
+ @concurrent static func decodedImage(_ data: Data, maxPixelSize: Int, maxPixelHeight: Int?) async throws(ImageDownloadError) -> (image: RSImage, byteCount: Int) {
+ let (imageSource, largestFrame) = try significantLargestFrame(data)
+
+ var longestSide = maxPixelSize
+ if let maxPixelHeight {
+ let isRotated = isRotatedQuarterTurn(imageSource, frameIndex: largestFrame.index)
+ let displayedWidth = isRotated ? largestFrame.height : largestFrame.width
+ let displayedHeight = isRotated ? largestFrame.width : largestFrame.height
+ longestSide = min(maxPixelSize, longestSideAtHeight(maxPixelHeight, width: displayedWidth, height: displayedHeight))
+ }
+
+ return try decodedResult(thumbnail(imageSource, frameIndex: largestFrame.index, maxPixelSize: longestSide))
+ }
+
+ /// Like `decodedImage(_:maxPixelSize:maxPixelHeight:)`, but decoded so the shorter side is `pixelSize`,
+ /// then cropped to a square from the bottom, left, and right, never the top, so faces are less likely to be cropped.
+ /// An image with a shorter side under `pixelSize` is cropped at its own size.
+ @concurrent static func decodedSquareImage(_ data: Data, pixelSize: Int) async throws(ImageDownloadError) -> (image: RSImage, byteCount: Int) {
+ let (imageSource, largestFrame) = try significantLargestFrame(data)
+
+ // The ratio of longer to shorter side is the same rotated or not.
+ let shorterSide = min(largestFrame.width, largestFrame.height)
+ let longerSide = max(largestFrame.width, largestFrame.height)
+ let longestSide = Int((Double(pixelSize) * Double(longerSide) / Double(shorterSide)).rounded(.up))
+
+ let cgImage = try thumbnail(imageSource, frameIndex: largestFrame.index, maxPixelSize: longestSide)
+ guard let squareImage = croppedToSquareFromTop(cgImage) else {
+ throw ImageDownloadError(statusCode: nil, decodingFailed: true, isTransient: false)
+ }
+ return decodedResult(squareImage)
+ }
+}
+
+private extension ThumbnailDownloader {
+
+ nonisolated static func significantLargestFrame(_ data: Data) throws(ImageDownloadError) -> (imageSource: CGImageSource, largestFrame: (index: Int, width: Int, height: Int)) {
+ guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil), let largestFrame = RSImage.largestFrame(in: imageSource) else {
+ throw ImageDownloadError(statusCode: nil, decodingFailed: true, isTransient: false)
+ }
+ guard SignificantImageFilter.hasSignificantDimensions(width: largestFrame.width, height: largestFrame.height) else {
+ throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: false, rejectedPixelSize: (width: largestFrame.width, height: largestFrame.height))
+ }
+ return (imageSource: imageSource, largestFrame: largestFrame)
+ }
+
+ /// In EXIF orientation, with its longest side no more than `maxPixelSize`.
+ nonisolated static func thumbnail(_ imageSource: CGImageSource, frameIndex: Int, maxPixelSize: Int) throws(ImageDownloadError) -> CGImage {
+ let options: [CFString: Any] = [
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceThumbnailMaxPixelSize: maxPixelSize,
+ kCGImageSourceShouldCacheImmediately: true
+ ]
+ guard let cgImage = CGImageSourceCreateThumbnailAtIndex(imageSource, frameIndex, options as CFDictionary) else {
+ throw ImageDownloadError(statusCode: nil, decodingFailed: true, isTransient: false)
+ }
+ return cgImage
+ }
+
+ /// Drawn into its own bitmap, since `CGImage.cropping(to:)` would keep the whole uncropped bitmap in memory.
+ /// Wider images lose equal amounts from the left and right. Taller images lose only from the bottom.
+ nonisolated static func croppedToSquareFromTop(_ cgImage: CGImage) -> CGImage? {
+ guard cgImage.width != cgImage.height else {
+ return cgImage
+ }
+ let side = min(cgImage.width, cgImage.height)
+ let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
+ guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB), let context = CGContext(data: nil, width: side, height: side, bitsPerComponent: squareBitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo) else {
+ return nil
+ }
+ // The context’s origin is at the bottom left, so the image’s top edge goes at y == side.
+ let drawRect = CGRect(x: -((cgImage.width - side) / 2), y: side - cgImage.height, width: cgImage.width, height: cgImage.height)
+ context.draw(cgImage, in: drawRect)
+ return context.makeImage()
+ }
+
+ nonisolated static func decodedResult(_ cgImage: CGImage) -> (image: RSImage, byteCount: Int) {
+ let byteCount = cgImage.bytesPerRow * cgImage.height
+ #if os(macOS)
+ return (image: NSImage(cgImage: cgImage, size: .zero), byteCount: byteCount)
+ #else
+ return (image: UIImage(cgImage: cgImage), byteCount: byteCount)
+ #endif
+ }
+
+ /// True when EXIF orientation swaps the frame’s width and height.
+ nonisolated private static func isRotatedQuarterTurn(_ imageSource: CGImageSource, frameIndex: Int) -> Bool {
+ let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, frameIndex, nil) as NSDictionary?
+ guard let rawOrientation = properties?[kCGImagePropertyOrientation] as? UInt32, let orientation = CGImagePropertyOrientation(rawValue: rawOrientation) else {
+ return false
+ }
+ switch orientation {
+ case .left, .leftMirrored, .right, .rightMirrored:
+ return true
+ case .up, .upMirrored, .down, .downMirrored:
+ return false
+ }
+ }
+
+ nonisolated private static func longestSideAtHeight(_ displayedHeight: Int, width: Int, height: Int) -> Int {
+ guard width > height else {
+ return displayedHeight
+ }
+ return Int((Double(displayedHeight) * Double(width) / Double(height)).rounded(.up))
+ }
+}
diff --git a/Modules/Images/Sources/Images/ThumbnailTaskQueue.swift b/Modules/Images/Sources/Images/ThumbnailTaskQueue.swift
new file mode 100644
index 000000000..cd9a7e960
--- /dev/null
+++ b/Modules/Images/Sources/Images/ThumbnailTaskQueue.swift
@@ -0,0 +1,115 @@
+//
+// ThumbnailTaskQueue.swift
+// Images
+//
+// Created by Brent Simmons on 10/25/26.
+//
+
+import Foundation
+
+enum ThumbnailTurn: Equatable, Sendable {
+ case dropped
+ case start
+ case startNow // Started by `startNow`
+}
+
+/// Decides when thumbnail tasks, such as downloads, may start, and limits how many run at once.
+///
+/// Tasks start most-recent-first, so images for rows the user just scrolled to go ahead
+/// of rows already scrolled past. A waiting task whose row is shown again moves to the front.
+///
+/// Tasks can have a group, such as a download’s host, so that a slow group can’t take every slot.
+///
+/// When too many are waiting, the oldest are dropped, since their rows are likely long gone.
+/// A dropped row that comes back asks again.
+@MainActor final class ThumbnailTaskQueue {
+
+ private struct WaitingTask {
+ let key: String
+ let group: String?
+ let continuation: CheckedContinuation
+ }
+
+ private let maximumRunningCount: Int
+ private let maximumWaitingCount: Int
+ private let maximumRunningCountPerGroup: Int
+ private var runningCount = 0
+ private var runningCountPerGroup = [String: Int]()
+ private var waiting = [WaitingTask]() // Next to start is last
+
+ var waitingCount: Int {
+ waiting.count
+ }
+
+ init(maximumRunningCount: Int, maximumWaitingCount: Int, maximumRunningCountPerGroup: Int = .max) {
+ self.maximumRunningCount = maximumRunningCount
+ self.maximumWaitingCount = maximumWaitingCount
+ self.maximumRunningCountPerGroup = maximumRunningCountPerGroup
+ }
+
+ /// Call `taskDidFinish` with the same group after the task finishes, unless it was dropped.
+ func waitForTurn(key: String, group: String? = nil) async -> ThumbnailTurn {
+ if runningCount < maximumRunningCount, hasRoom(in: group) {
+ noteTaskStarted(group: group)
+ return .start
+ }
+ return await withCheckedContinuation { continuation in
+ waiting.append(WaitingTask(key: key, group: group, continuation: continuation))
+ if waiting.count > maximumWaitingCount {
+ waiting.removeFirst().continuation.resume(returning: .dropped)
+ }
+ }
+ }
+
+ func taskDidFinish(group: String? = nil) {
+ runningCount -= 1
+ if let group {
+ runningCountPerGroup[group, default: 0] -= 1
+ if runningCountPerGroup[group] == 0 {
+ runningCountPerGroup[group] = nil
+ }
+ }
+
+ guard runningCount < maximumRunningCount, let index = waiting.lastIndex(where: { hasRoom(in: $0.group) }) else {
+ return
+ }
+ let next = waiting.remove(at: index)
+ noteTaskStarted(group: next.group)
+ next.continuation.resume(returning: .start)
+ }
+
+ /// Moves a waiting task to the front.
+ func prioritize(key: String) {
+ guard let index = waiting.lastIndex(where: { $0.key == key }) else {
+ return
+ }
+ waiting.append(waiting.remove(at: index))
+ }
+
+ /// Starts a waiting task now, even when that goes over the limit.
+ func startNow(key: String) {
+ guard let index = waiting.lastIndex(where: { $0.key == key }) else {
+ return
+ }
+ let waitingTask = waiting.remove(at: index)
+ noteTaskStarted(group: waitingTask.group)
+ waitingTask.continuation.resume(returning: .startNow)
+ }
+}
+
+private extension ThumbnailTaskQueue {
+
+ func hasRoom(in group: String?) -> Bool {
+ guard let group else {
+ return true
+ }
+ return runningCountPerGroup[group, default: 0] < maximumRunningCountPerGroup
+ }
+
+ func noteTaskStarted(group: String?) {
+ runningCount += 1
+ if let group {
+ runningCountPerGroup[group, default: 0] += 1
+ }
+ }
+}
diff --git a/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift
new file mode 100644
index 000000000..03ba674cc
--- /dev/null
+++ b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift
@@ -0,0 +1,137 @@
+//
+// ArticleThumbnailFinderTests.swift
+// ImagesTests
+//
+// Created by Brent Simmons on 10/25/26.
+//
+
+import Foundation
+import Testing
+import Articles
+import RSWeb
+@testable import Images
+
+/// Swift Testing also has an `Attachment` type.
+private typealias ArticleAttachment = Articles.Attachment
+
+@MainActor @Suite struct ArticleThumbnailFinderTests {
+
+ @Test func smallModePrefersThumbnailAndLargeModePrefersImage() throws {
+ let finder = ArticleThumbnailFinder(imageDatabase: ImageDatabase(databasePath: ":memory:"))
+ let attachment = try #require(ArticleAttachment(url: "https://example.com/attachment.jpg", mimeType: "image/jpeg", title: nil, sizeInBytes: nil, durationInSeconds: nil, width: 1200, height: 800, medium: nil))
+ let article = makeArticle(imageURL: "https://example.com/image.jpg", thumbnailURL: "https://example.com/thumbnail.jpg", attachments: [attachment])
+
+ #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/thumbnail.jpg")
+ #expect(finder.thumbnailURL(for: article, mode: .large) == "https://example.com/image.jpg")
+ }
+
+ @Test func largeModePrefersHTMLImageToBloggerSquareThumbnail() {
+ let finder = ArticleThumbnailFinder(imageDatabase: ImageDatabase(databasePath: ":memory:"))
+ let bloggerThumbnailURL = "https://blogger.googleusercontent.com/img/b/photo/s72-w424-h353-c/202610211751.jpg"
+ let bloggerImageURL = "https://blogger.googleusercontent.com/img/b/photo/w424-h353/202610211751.jpg"
+ let article = makeArticle(contentHTML: "
", thumbnailURL: bloggerThumbnailURL)
+ let articleWithNoHTMLImage = makeArticle(articleID: "2", contentHTML: "No images.
", thumbnailURL: bloggerThumbnailURL)
+
+ #expect(finder.thumbnailURL(for: article, mode: .large) == bloggerImageURL)
+ #expect(finder.thumbnailURL(for: article, mode: .small) == bloggerThumbnailURL)
+ #expect(finder.thumbnailURL(for: articleWithNoHTMLImage, mode: .large) == bloggerThumbnailURL)
+ }
+
+ @Test func failedImageFallsThroughToNextSource() {
+ let imageDatabase = ImageDatabase(databasePath: ":memory:")
+ let finder = ArticleThumbnailFinder(imageDatabase: imageDatabase)
+ let article = makeArticle(imageURL: "https://example.com/image.jpg", thumbnailURL: "https://example.com/thumbnail.jpg")
+
+ imageDatabase.recordFailure(url: "https://example.com/thumbnail.jpg")
+
+ #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/image.jpg")
+ }
+
+ @Test func insignificantDimensionsFallThroughButAreNotAFailure() {
+ let imageDatabase = ImageDatabase(databasePath: ":memory:")
+ let finder = ArticleThumbnailFinder(imageDatabase: imageDatabase)
+ let article = makeArticle(imageURL: "https://example.com/image.jpg", thumbnailURL: "https://example.com/logo.png")
+
+ imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: "https://example.com/logo.png", pixelSize: (width: 48, height: 48), conditionalGetInfo: nil, nextCheck: Date(), isIcon: false))
+
+ #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/image.jpg")
+ #expect(!imageDatabase.recentlyFailed(url: "https://example.com/logo.png"))
+ }
+
+ @Test func htmlThumbnailIsDiscovered() async {
+ let imageDatabase = ImageDatabase(databasePath: ":memory:")
+ let finder = ArticleThumbnailFinder(imageDatabase: imageDatabase)
+ let html = """
+
+
+
+ """
+ let articleWithImage = makeArticle(articleID: "1", contentHTML: html)
+ let articleWithoutImage = makeArticle(articleID: "2", contentHTML: "No images.
")
+
+ 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)
+
+ imageDatabase.recordFailure(url: "https://example.com/uploads/photo.jpg")
+ finder.thumbnailURLDidFail("https://example.com/uploads/photo.jpg")
+ #expect(finder.thumbnailURL(for: articleWithImage, mode: .small) == "https://example.com/uploads/second-photo.jpg")
+ }
+
+ @Test func failedProvidedImageFallsBackToHTMLThumbnail() async {
+ let imageDatabase = ImageDatabase(databasePath: ":memory:")
+ let finder = ArticleThumbnailFinder(imageDatabase: imageDatabase)
+ let article = makeArticle(contentHTML: #"
"#, thumbnailURL: "https://example.com/thumbnail.jpg")
+
+ 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")
+ finder.thumbnailURLDidFail("https://example.com/thumbnail.jpg")
+ #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/uploads/photo.jpg")
+ }
+
+ @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.handleLowMemory(Notification(name: .lowMemory))
+ #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/uploads/photo.jpg")
+ }
+
+ @Test func nonImageResponseMovesToNextSourceUntilNetworkChanges() {
+ let finder = ArticleThumbnailFinder(imageDatabase: ImageDatabase(databasePath: ":memory:"))
+ let article = makeArticle(imageURL: "https://example.com/image.jpg", thumbnailURL: "https://example.com/thumbnail.jpg")
+ #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/thumbnail.jpg")
+
+ finder.thumbnailDidFail(url: "https://example.com/thumbnail.jpg", error: ImageDownloadError(statusCode: 200, decodingFailed: true, isTransient: true))
+ #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/image.jpg")
+
+ finder.handleNetworkStatusDidChange(Notification(name: .networkStatusDidChange))
+ #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/thumbnail.jpg")
+ }
+
+ @Test func newArticleInstanceReusesChosenURLUnlessItsImagesChanged() {
+ let imageDatabase = ImageDatabase(databasePath: ":memory:")
+ let finder = ArticleThumbnailFinder(imageDatabase: imageDatabase)
+ let article = makeArticle(imageURL: "https://example.com/image.jpg", thumbnailURL: "https://example.com/thumbnail.jpg")
+ #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/thumbnail.jpg")
+
+ // A failure with no notification shows whether the choice was made again.
+ imageDatabase.recordFailure(url: "https://example.com/thumbnail.jpg")
+
+ let sameImages = makeArticle(contentHTML: "Edited.
", imageURL: "https://example.com/image.jpg", thumbnailURL: "https://example.com/thumbnail.jpg")
+ #expect(finder.thumbnailURL(for: sameImages, mode: .small) == "https://example.com/thumbnail.jpg")
+
+ let differentImages = makeArticle(imageURL: "https://example.com/new-image.jpg", thumbnailURL: "https://example.com/thumbnail.jpg")
+ #expect(finder.thumbnailURL(for: differentImages, mode: .small) == "https://example.com/new-image.jpg")
+ }
+}
+
+// MARK: - Helpers
+
+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/Modules/Images/Tests/ImagesTests/DownloadedImageCacheTests.swift b/Modules/Images/Tests/ImagesTests/DownloadedImageCacheTests.swift
new file mode 100644
index 000000000..3b7be307c
--- /dev/null
+++ b/Modules/Images/Tests/ImagesTests/DownloadedImageCacheTests.swift
@@ -0,0 +1,170 @@
+//
+// DownloadedImageCacheTests.swift
+// ImagesTests
+//
+// Created by Brent Simmons on 10/26/26.
+//
+
+import Foundation
+import Testing
+import RSCore
+@testable import Images
+
+@Suite struct DownloadedImageCacheTests {
+
+ @Test func leastRecentlyUsedImagesAreRemovedDownToLimit() async {
+ let now = Date()
+ let longAgo = now.addingTimeInterval(-TimeInterval(days: 10))
+ let urls = ["https://example.com/a.jpg", "https://example.com/b.jpg", "https://example.com/c.jpg", "https://example.com/just-saved.jpg"]
+ let records = [
+ DownloadedImageUsage(url: "https://example.com/no-file.jpg", lastAccessed: longAgo, isIcon: false),
+ DownloadedImageUsage(url: urls[0], lastAccessed: longAgo, isIcon: false),
+ DownloadedImageUsage(url: urls[1], lastAccessed: longAgo, isIcon: false),
+ DownloadedImageUsage(url: urls[2], lastAccessed: longAgo, isIcon: false),
+ DownloadedImageUsage(url: urls[3], lastAccessed: now, isIcon: false)
+ ]
+ let keys = urls.map { DownloadedImageCache.diskKey($0) }
+ var files = Dictionary(uniqueKeysWithValues: keys.map { ($0, storedFile(longAgo, byteCount: 100)) })
+ files["unrecorded"] = storedFile(longAgo, byteCount: 100)
+ files["unrecordedJustSaved"] = storedFile(now, byteCount: 100)
+
+ let removal = await DownloadedImageCache.imageRemoval(records: records, files: files, urlsInUse: [], now: now, maximumByteCount: 350)
+
+ #expect(removal.urls == ["https://example.com/no-file.jpg", urls[0]])
+ #expect(removal.keys == ["unrecorded", keys[0]])
+ #expect(removal.remainingByteCount == 300)
+ }
+
+ @Test func imagesInUseAreKept() async {
+ let now = Date()
+ let longAgo = now.addingTimeInterval(-TimeInterval(days: 10))
+ let records = (0..<3).map { DownloadedImageUsage(url: "https://example.com/\($0).jpg", lastAccessed: longAgo, isIcon: false) }
+ let files = Dictionary(uniqueKeysWithValues: records.map { (DownloadedImageCache.diskKey($0.url), storedFile(longAgo, byteCount: 100)) })
+
+ let removal = await DownloadedImageCache.imageRemoval(records: records, files: files, urlsInUse: [records[0].url], now: now, maximumByteCount: 200)
+
+ #expect(removal.urls == [records[1].url])
+ #expect(removal.remainingByteCount == 200)
+ }
+
+ @Test func derivedCopiesAreKeptAndRemovedWithTheirImages() async {
+ let now = Date()
+ let longAgo = now.addingTimeInterval(-TimeInterval(days: 10))
+ let records = (0..<2).map { DownloadedImageUsage(url: "https://example.com/\($0).png", lastAccessed: longAgo.addingTimeInterval(TimeInterval($0)), isIcon: false) }
+ let removedCopy = DownloadedImageCache.derivedDiskKey(records[0].url, suffix: "144")
+ let keptCopy = DownloadedImageCache.derivedDiskKey(records[1].url, suffix: "144")
+ let orphanedCopy = DownloadedImageCache.derivedDiskKey("https://example.com/gone.png", suffix: "144")
+ var files = Dictionary(uniqueKeysWithValues: records.map { (DownloadedImageCache.diskKey($0.url), storedFile(longAgo, byteCount: 100)) })
+ for key in [removedCopy, keptCopy, orphanedCopy] {
+ files[key] = storedFile(longAgo, byteCount: 10)
+ }
+
+ let removal = await DownloadedImageCache.imageRemoval(records: records, files: files, urlsInUse: [], now: now, maximumByteCount: 150)
+
+ #expect(removal.urls == [records[0].url])
+ #expect(removal.keys == [DownloadedImageCache.diskKey(records[0].url), removedCopy, orphanedCopy])
+ #expect(removal.remainingByteCount == 100)
+ }
+
+ @Test func iconsDoNotCountTowardLimit() async {
+ let now = Date()
+ let longAgo = now.addingTimeInterval(-TimeInterval(days: 10))
+ let icon = DownloadedImageUsage(url: "https://example.com/apple-touch-icon.png", lastAccessed: longAgo, isIcon: true)
+ let thumbnails = (0..<2).map { DownloadedImageUsage(url: "https://example.com/\($0).jpg", lastAccessed: longAgo.addingTimeInterval(TimeInterval($0 + 1)), isIcon: false) }
+ let records = [icon] + thumbnails
+ let files = Dictionary(uniqueKeysWithValues: records.map { (DownloadedImageCache.diskKey($0.url), storedFile(longAgo, byteCount: 100)) })
+
+ let removal = await DownloadedImageCache.imageRemoval(records: records, files: files, urlsInUse: [], now: now, maximumByteCount: 100)
+
+ #expect(removal.urls == [thumbnails[0].url])
+ #expect(removal.remainingByteCount == 100)
+ }
+
+ @Test func iconsNotUsedIn180DaysAreRemoved() async {
+ let now = Date()
+ let unusedIcon = DownloadedImageUsage(url: "https://example.com/deleted-feed-icon.png", lastAccessed: now.addingTimeInterval(-TimeInterval(days: 181)), isIcon: true)
+ let usedIcon = DownloadedImageUsage(url: "https://example.com/feed-icon.png", lastAccessed: now.addingTimeInterval(-TimeInterval(days: 179)), isIcon: true)
+ let records = [unusedIcon, usedIcon]
+ let files = Dictionary(uniqueKeysWithValues: records.map { (DownloadedImageCache.diskKey($0.url), storedFile(unusedIcon.lastAccessed, byteCount: 100)) })
+
+ let removal = await DownloadedImageCache.imageRemoval(records: records, files: files, urlsInUse: [], now: now, maximumByteCount: 1000)
+
+ #expect(removal.urls == [unusedIcon.url])
+ #expect(removal.keys == [DownloadedImageCache.diskKey(unusedIcon.url)])
+ }
+
+ @Test func iconWithOnlyItsScaledCopyIsKept() async {
+ let now = Date()
+ let longAgo = now.addingTimeInterval(-TimeInterval(days: 10))
+ let icon = DownloadedImageUsage(url: "https://example.com/og-image.jpg", lastAccessed: longAgo, isIcon: true)
+ let files = [DownloadedImageCache.derivedDiskKey(icon.url, suffix: "144"): storedFile(longAgo, byteCount: 10)]
+
+ let removal = await DownloadedImageCache.imageRemoval(records: [icon], files: files, urlsInUse: [], now: now, maximumByteCount: 1000)
+
+ #expect(removal.urls.isEmpty)
+ #expect(removal.keys.isEmpty)
+ }
+
+ @Test func folderThatCantBeListedHasNoStoredFiles() async {
+ let missingFolder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).path
+ let files = await DownloadedImageCache.storedFiles(BinaryDiskCache(folder: missingFolder))
+ #expect(files == nil)
+ }
+
+ @Test func storedFilesHaveTheirSizesOnDisk() async throws {
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent("DownloadedImageCacheTests-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ defer {
+ try? FileManager.default.removeItem(at: folder)
+ }
+ let diskCache = BinaryDiskCache(folder: folder.path)
+ let key = DownloadedImageCache.diskKey("https://example.com/photo.jpg")
+ try diskCache.setData(Data(count: 1234), forKey: key)
+
+ let files = await DownloadedImageCache.storedFiles(diskCache)
+ #expect(files?[key]?.byteCount == 1234)
+ }
+
+ @Test func shortMaxAgeIsRaisedToThreeDays() throws {
+ let url = try #require(URL(string: "https://example.com/icon.png"))
+ let httpResponse = try #require(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: ["Cache-Control": "max-age=60", "ETag": "\"abc\""]))
+
+ let interval = DownloadedImageCache.nextCheck(httpResponse, hasValidators: true).timeIntervalSinceNow
+ #expect(interval > TimeInterval(days: 3) * 0.8 - 60 && interval < TimeInterval(days: 3) * 1.2)
+ }
+
+ @Test func imageWithoutValidatorsWaitsLongestBetweenChecks() throws {
+ let url = try #require(URL(string: "https://example.com/icon.png"))
+ let httpResponse = try #require(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: ["Cache-Control": "max-age=60"]))
+
+ let interval = DownloadedImageCache.nextCheck(httpResponse, hasValidators: false).timeIntervalSinceNow
+ #expect(interval > TimeInterval(days: 30) * 0.8 - 60 && interval < TimeInterval(days: 30) * 1.2)
+ }
+
+ @Test func serverErrorsAndRateLimitsAreTransientButMissingImagesAreNot() {
+ #expect(DownloadedImageCache.isTransient(statusCode: 503))
+ #expect(DownloadedImageCache.isTransient(statusCode: 429))
+ #expect(DownloadedImageCache.isTransient(statusCode: 408))
+ #expect(!DownloadedImageCache.isTransient(statusCode: 404))
+ #expect(!DownloadedImageCache.isTransient(statusCode: 403))
+ }
+
+ @Test func longerRetryAfterExtendsWaitAndLaterFailureDoesNotShortenIt() {
+ let now = Date()
+ let retryAfter = TimeInterval(days: 1)
+ let firstRetryDate = DownloadedImageCache.retryDate(after: nil, retryAfter: nil, now: now)
+
+ let retryDateFromRetryAfter = DownloadedImageCache.retryDate(after: firstRetryDate, retryAfter: retryAfter, now: now)
+ #expect(retryDateFromRetryAfter == now.addingTimeInterval(retryAfter))
+
+ let retryDateAfterLaterFailure = DownloadedImageCache.retryDate(after: retryDateFromRetryAfter, retryAfter: nil, now: now.addingTimeInterval(1))
+ #expect(retryDateAfterLaterFailure == retryDateFromRetryAfter)
+ }
+}
+
+private extension DownloadedImageCacheTests {
+
+ func storedFile(_ modificationDate: Date, byteCount: Int) -> DownloadedImageCache.StoredFile {
+ DownloadedImageCache.StoredFile(modificationDate: modificationDate, byteCount: byteCount)
+ }
+}
diff --git a/Modules/Images/Tests/ImagesTests/GrayscaleIconImageTests.swift b/Modules/Images/Tests/ImagesTests/GrayscaleIconImageTests.swift
new file mode 100644
index 000000000..4d708debf
--- /dev/null
+++ b/Modules/Images/Tests/ImagesTests/GrayscaleIconImageTests.swift
@@ -0,0 +1,67 @@
+//
+// GrayscaleIconImageTests.swift
+// ImagesTests
+//
+// Created by Brent Simmons on 11/9/26.
+//
+
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+import Testing
+import RSCore
+@testable import Images
+
+@Suite struct GrayscaleIconImageTests {
+
+ @Test func redIconBecomesGrayAndKeepsAlpha() throws {
+ let iconImage = IconImage(try halfTransparentRedImage())
+ let grayscaleIconImage = iconImage.grayscaleIconImage
+ #expect(grayscaleIconImage === iconImage.grayscaleIconImage)
+
+ let pixel = try firstPixel(grayscaleIconImage.image)
+ #expect(pixel.red == pixel.green)
+ #expect(pixel.green == pixel.blue)
+ #expect(pixel.red > 0)
+ #expect(pixel.alpha == 128)
+ }
+}
+
+private extension GrayscaleIconImageTests {
+
+ static let dimension = 2
+
+ func halfTransparentRedImage() throws -> RSImage {
+ let context = try #require(bitmapContext())
+ context.setFillColor(CGColor(srgbRed: 1, green: 0, blue: 0, alpha: 128.0 / 255.0))
+ context.fill(CGRect(x: 0, y: 0, width: Self.dimension, height: Self.dimension))
+ let cgImage = try #require(context.makeImage())
+ #if os(macOS)
+ return NSImage(cgImage: cgImage, size: CGSize(width: Self.dimension, height: Self.dimension))
+ #else
+ return UIImage(cgImage: cgImage)
+ #endif
+ }
+
+ func firstPixel(_ image: RSImage) throws -> (red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
+ #if os(macOS)
+ let cgImage = try #require(image.cgImage(forProposedRect: nil, context: nil, hints: nil))
+ #else
+ let cgImage = try #require(image.cgImage)
+ #endif
+ let context = try #require(bitmapContext())
+ context.draw(cgImage, in: CGRect(x: 0, y: 0, width: Self.dimension, height: Self.dimension))
+ let pixels = try #require(context.data).bindMemory(to: UInt8.self, capacity: 4)
+ return (pixels[0], pixels[1], pixels[2], pixels[3])
+ }
+
+ func bitmapContext() -> CGContext? {
+ guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else {
+ return nil
+ }
+ let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
+ return CGContext(data: nil, width: Self.dimension, height: Self.dimension, bitsPerComponent: 8, bytesPerRow: Self.dimension * 4, space: colorSpace, bitmapInfo: bitmapInfo)
+ }
+}
diff --git a/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift b/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift
new file mode 100644
index 000000000..d8fdd86b4
--- /dev/null
+++ b/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift
@@ -0,0 +1,154 @@
+//
+// ImageDatabaseTests.swift
+// ImagesTests
+//
+// Created by Brent Simmons on 10/27/26.
+//
+
+import Foundation
+import Testing
+import RSDatabase
+import RSDatabaseObjC
+import RSWeb
+@testable import Images
+
+@MainActor @Suite struct ImageDatabaseTests {
+
+ @Test func legacyDatabaseIsImportedAndDeleted() async throws {
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent("ImageDatabaseTests-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ defer {
+ try? FileManager.default.removeItem(at: folder)
+ }
+ let databasePath = folder.appendingPathComponent("Images.db").path
+ let legacyDatabasePath = folder.appendingPathComponent("ImageMetadata.db").path
+ writeLegacyDatabase(path: legacyDatabasePath)
+
+ let imageDatabase = ImageDatabase(databasePath: databasePath, legacyDatabasePath: legacyDatabasePath)
+
+ #expect(imageDatabase.faviconURL(forHomePageURL: "https://example.com/") == "https://example.com/favicon.ico")
+ #expect(imageDatabase.recentlyFailed(url: "https://example.com/missing.png"))
+ #expect(!FileManager.default.fileExists(atPath: legacyDatabasePath))
+
+ // Waits for the cleanup init queues, which would otherwise run after the folder is deleted.
+ await imageDatabase.vacuum()
+ }
+
+ @Test func homePageIconsAreSavedAndReloaded() async throws {
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent("ImageDatabaseTests-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ defer {
+ try? FileManager.default.removeItem(at: folder)
+ }
+ let databasePath = folder.appendingPathComponent("Images.db").path
+ let homePageURL = "https://daringfireball.net/"
+ let iconURL = "https://daringfireball.net/graphics/apple-touch-icon.png"
+ let homePageURLWithNoIcon = "https://inessential.com/"
+
+ let imageDatabase = ImageDatabase(databasePath: databasePath)
+ imageDatabase.saveHomePageIcon(homePageURL: homePageURL, iconURL: iconURL)
+ imageDatabase.saveHomePageIcon(homePageURL: homePageURLWithNoIcon, iconURL: nil)
+
+ // Waits for the saves, so the database opened below sees them.
+ await imageDatabase.vacuum()
+
+ let reopenedImageDatabase = ImageDatabase(databasePath: databasePath)
+ for database in [imageDatabase, reopenedImageDatabase] {
+ #expect(database.homePageIconURL(forHomePageURL: homePageURL) == iconURL)
+ #expect(!database.homePageHasNoIcon(homePageURL))
+ #expect(database.homePageIconURL(forHomePageURL: homePageURLWithNoIcon) == nil)
+ #expect(database.homePageHasNoIcon(homePageURLWithNoIcon))
+ }
+
+ // Waits for the cleanup init queues, which would otherwise run after the folder is deleted.
+ await reopenedImageDatabase.vacuum()
+ }
+
+ @Test func failedUsageQueryReturnsNil() {
+ let database = FMDatabase.openAndSetUpDatabase(path: ":memory:")
+ defer {
+ database.close()
+ }
+ #expect(DownloadedImageTable.fetchUsageByLeastRecentAccess(database: database) == nil)
+ }
+
+ @Test func downloadedImagesAreSavedAndCheckedForThumbnailSuitability() async throws {
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent("ImageDatabaseTests-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ defer {
+ try? FileManager.default.removeItem(at: folder)
+ }
+ let databasePath = folder.appendingPathComponent("Images.db").path
+ let iconURL = "https://example.com/icon.png"
+ let replacedIconURL = "https://example.com/replaced-icon.png"
+ let photoURL = "https://example.com/photo.jpg"
+ let unreadableImageURL = "https://example.com/unreadable.png"
+ let nextCheck = Date(timeIntervalSince1970: 2_000_000_000)
+ let conditionalGetInfo = try #require(HTTPConditionalGetInfo(lastModified: nil, etag: "\"abc\""))
+
+ let imageDatabase = ImageDatabase(databasePath: databasePath)
+ imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: iconURL, pixelSize: (width: 48, height: 48), conditionalGetInfo: nil, nextCheck: nextCheck, isIcon: false))
+ imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: replacedIconURL, pixelSize: (width: 48, height: 48), conditionalGetInfo: nil, nextCheck: nextCheck, isIcon: false))
+ imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: replacedIconURL, pixelSize: (width: 512, height: 512), conditionalGetInfo: nil, nextCheck: nextCheck, isIcon: false))
+ imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: photoURL, pixelSize: (width: 800, height: 600), conditionalGetInfo: conditionalGetInfo, nextCheck: nextCheck, isIcon: false))
+ imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: unreadableImageURL, pixelSize: nil, conditionalGetInfo: nil, nextCheck: nextCheck, isIcon: false))
+
+ let validation = await imageDatabase.fetchDownloadedImageValidation(url: photoURL)
+ #expect(validation?.conditionalGetInfo == conditionalGetInfo)
+ #expect(validation?.nextCheck == nextCheck)
+
+ // Waits for the saves, so the database opened below sees them.
+ await imageDatabase.vacuum()
+
+ let reopenedImageDatabase = ImageDatabase(databasePath: databasePath)
+ for database in [imageDatabase, reopenedImageDatabase] {
+ #expect(database.isUnsuitableForThumbnail(url: iconURL))
+ #expect(!database.isUnsuitableForThumbnail(url: replacedIconURL))
+ #expect(!database.isUnsuitableForThumbnail(url: photoURL))
+ #expect(database.isUnsuitableForThumbnail(url: unreadableImageURL))
+ }
+
+ // Waits for the cleanup init queues, which would otherwise run after the folder is deleted.
+ await reopenedImageDatabase.vacuum()
+ }
+
+ @Test func newValidatorsAreSavedWithNextCheck() async throws {
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent("ImageDatabaseTests-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ defer {
+ try? FileManager.default.removeItem(at: folder)
+ }
+ let databasePath = folder.appendingPathComponent("Images.db").path
+ let iconURL = "https://example.com/apple-touch-icon.png"
+ let oldConditionalGetInfo = try #require(HTTPConditionalGetInfo(lastModified: nil, etag: "\"old\""))
+ let newConditionalGetInfo = try #require(HTTPConditionalGetInfo(lastModified: "Tue, 03 Nov 2026 12:00:00 GMT", etag: "\"new\""))
+ let nextCheck = Date(timeIntervalSince1970: 2_000_000_000)
+ let laterNextCheck = Date(timeIntervalSince1970: 2_100_000_000)
+
+ let imageDatabase = ImageDatabase(databasePath: databasePath)
+ imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: iconURL, pixelSize: (width: 180, height: 180), conditionalGetInfo: oldConditionalGetInfo, nextCheck: nextCheck, isIcon: true))
+ imageDatabase.saveDownloadedImageNextCheck(url: iconURL, nextCheck: laterNextCheck, conditionalGetInfo: newConditionalGetInfo)
+
+ let validation = await imageDatabase.fetchDownloadedImageValidation(url: iconURL)
+ #expect(validation?.conditionalGetInfo == newConditionalGetInfo)
+ #expect(validation?.nextCheck == laterNextCheck)
+
+ // Waits for the cleanup init queues, which would otherwise run after the folder is deleted.
+ await imageDatabase.vacuum()
+ }
+}
+
+private extension ImageDatabaseTests {
+
+ func writeLegacyDatabase(path: String) {
+ let database = FMDatabase.openAndSetUpDatabase(path: path)
+ let lastChecked = Date().timeIntervalSince1970
+ database.executeStatements("""
+ CREATE TABLE downloadFailure (url TEXT PRIMARY KEY NOT NULL, statusCode INTEGER, lastChecked REAL NOT NULL);
+ CREATE TABLE homePageFavicon (homePageURL TEXT PRIMARY KEY NOT NULL, faviconURL TEXT, lastChecked REAL NOT NULL);
+ """)
+ database.executeUpdate("INSERT INTO downloadFailure (url, statusCode, lastChecked) VALUES (?, ?, ?)", withArgumentsIn: ["https://example.com/missing.png", 404, lastChecked])
+ database.executeUpdate("INSERT INTO homePageFavicon (homePageURL, faviconURL, lastChecked) VALUES (?, ?, ?)", withArgumentsIn: ["https://example.com/", "https://example.com/favicon.ico", lastChecked])
+ database.close()
+ }
+}
diff --git a/Modules/Images/Tests/ImagesTests/ThumbnailDownloaderTests.swift b/Modules/Images/Tests/ImagesTests/ThumbnailDownloaderTests.swift
new file mode 100644
index 000000000..18d93116a
--- /dev/null
+++ b/Modules/Images/Tests/ImagesTests/ThumbnailDownloaderTests.swift
@@ -0,0 +1,138 @@
+//
+// ThumbnailDownloaderTests.swift
+// ImagesTests
+//
+// Created by Brent Simmons on 11/3/26.
+//
+
+import Foundation
+import Testing
+import CoreGraphics
+import ImageIO
+import UniformTypeIdentifiers
+import RSCore
+@testable import Images
+
+@MainActor @Suite struct ThumbnailDownloaderTests {
+
+ @Test func thumbnailTooSmallIsRejected() async throws {
+ let smallImageData = try #require(jpegData(width: 48, height: 48))
+
+ await #expect {
+ _ = try await ThumbnailDownloader.decodedImage(smallImageData, maxPixelSize: 512, maxPixelHeight: nil)
+ } throws: { error in
+ (error as? ImageDownloadError)?.rejectedPixelSize?.width == 48
+ }
+ }
+
+ @Test func thumbnailIsDecodedInEXIFOrientation() async throws {
+ let rotatedImageData = try #require(jpegData(width: 400, height: 200, orientation: .right))
+
+ let decodedImage = try await ThumbnailDownloader.decodedImage(rotatedImageData, maxPixelSize: 512, maxPixelHeight: nil)
+ #expect(decodedImage.image.size == CGSize(width: 200, height: 400))
+ }
+
+ @Test func largestFrameOfMultiImageFileIsDecoded() async throws {
+ let imageData = try #require(tiffData(frameSizes: [(width: 48, height: 48), (width: 400, height: 200)]))
+
+ let decodedImage = try await ThumbnailDownloader.decodedImage(imageData, maxPixelSize: 512, maxPixelHeight: nil)
+ #expect(decodedImage.image.size == CGSize(width: 400, height: 200))
+ }
+
+ @Test func largeThumbnailIsDecodedToItsDisplayedHeight() async throws {
+ let landscapeImageData = try #require(jpegData(width: 1500, height: 1000))
+ let landscapeImage = try await ThumbnailDownloader.decodedImage(landscapeImageData, maxPixelSize: 1200, maxPixelHeight: 360)
+ #expect(landscapeImage.image.size == CGSize(width: 540, height: 360))
+
+ // Stored taller than wide, displayed wider than tall.
+ let rotatedImageData = try #require(jpegData(width: 1000, height: 1500, orientation: .right))
+ let rotatedImage = try await ThumbnailDownloader.decodedImage(rotatedImageData, maxPixelSize: 1200, maxPixelHeight: 360)
+ #expect(rotatedImage.image.size == CGSize(width: 540, height: 360))
+
+ let wideImageData = try #require(jpegData(width: 2000, height: 500))
+ let wideImage = try await ThumbnailDownloader.decodedImage(wideImageData, maxPixelSize: 1200, maxPixelHeight: 360)
+ #expect(wideImage.image.size == CGSize(width: 1200, height: 300))
+ }
+
+ @Test func smallThumbnailIsCroppedFromTheBottomOfATallImage() async throws {
+ // Top half red, bottom half blue: the square is the top half, so it’s red. A centered square would be blue near its bottom.
+ // The bottom row itself is blended with the first blue row by scaling, so the pixel checked is a little above it.
+ let portraitImageData = try #require(jpegData(width: 300, height: 600, topHalfRed: true))
+ let decodedImage = try await ThumbnailDownloader.decodedSquareImage(portraitImageData, pixelSize: 256)
+ #expect(decodedImage.image.size == CGSize(width: 256, height: 256))
+
+ let nearBottomPixel = try #require(pixel(decodedImage.image, x: 128, yFromTop: 224))
+ #expect(nearBottomPixel.red > 200 && nearBottomPixel.blue < 50)
+ }
+}
+
+// MARK: - Helpers
+
+private func makeImage(width: Int, height: Int, topHalfRed: Bool = false) -> CGImage? {
+ guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else {
+ return nil
+ }
+ if topHalfRed {
+ context.setFillColor(red: 0, green: 0, blue: 1, alpha: 1)
+ context.fill(CGRect(x: 0, y: 0, width: width, height: height / 2))
+ context.setFillColor(red: 1, green: 0, blue: 0, alpha: 1)
+ context.fill(CGRect(x: 0, y: height / 2, width: width, height: height - height / 2))
+ } else {
+ context.setFillColor(red: 0.2, green: 0.4, blue: 0.6, alpha: 1)
+ context.fill(CGRect(x: 0, y: 0, width: width, height: height))
+ }
+ return context.makeImage()
+}
+
+private func pixel(_ image: RSImage, x: Int, yFromTop: Int) -> (red: UInt8, blue: UInt8)? {
+ #if os(macOS)
+ guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
+ return nil
+ }
+ #else
+ guard let cgImage = image.cgImage else {
+ return nil
+ }
+ #endif
+ var bytes = [UInt8](repeating: 0, count: 4)
+ let didDraw = bytes.withUnsafeMutableBytes { buffer -> Bool in
+ guard let context = CGContext(data: buffer.baseAddress, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else {
+ return false
+ }
+ // Places the requested pixel at the 1×1 context’s origin, which is at the bottom left.
+ context.draw(cgImage, in: CGRect(x: -x, y: yFromTop - (cgImage.height - 1), width: cgImage.width, height: cgImage.height))
+ return true
+ }
+ guard didDraw else {
+ return nil
+ }
+ return (red: bytes[0], blue: bytes[2])
+}
+
+private func tiffData(frameSizes: [(width: Int, height: Int)]) -> Data? {
+ guard let mutableData = CFDataCreateMutable(nil, 0), let destination = CGImageDestinationCreateWithData(mutableData, UTType.tiff.identifier as CFString, frameSizes.count, nil) else {
+ return nil
+ }
+ for frameSize in frameSizes {
+ guard let cgImage = makeImage(width: frameSize.width, height: frameSize.height) else {
+ return nil
+ }
+ CGImageDestinationAddImage(destination, cgImage, nil)
+ }
+ guard CGImageDestinationFinalize(destination) else {
+ return nil
+ }
+ return mutableData as Data
+}
+
+private func jpegData(width: Int, height: Int, orientation: CGImagePropertyOrientation = .up, topHalfRed: Bool = false) -> Data? {
+ guard let cgImage = makeImage(width: width, height: height, topHalfRed: topHalfRed), let mutableData = CFDataCreateMutable(nil, 0), let destination = CGImageDestinationCreateWithData(mutableData, UTType.jpeg.identifier as CFString, 1, nil) else {
+ return nil
+ }
+ let properties = [kCGImagePropertyOrientation: orientation.rawValue] as CFDictionary
+ CGImageDestinationAddImage(destination, cgImage, properties)
+ guard CGImageDestinationFinalize(destination) else {
+ return nil
+ }
+ return mutableData as Data
+}
diff --git a/Modules/Images/Tests/ImagesTests/ThumbnailTaskQueueTests.swift b/Modules/Images/Tests/ImagesTests/ThumbnailTaskQueueTests.swift
new file mode 100644
index 000000000..2b1c4c79b
--- /dev/null
+++ b/Modules/Images/Tests/ImagesTests/ThumbnailTaskQueueTests.swift
@@ -0,0 +1,92 @@
+//
+// ThumbnailTaskQueueTests.swift
+// ImagesTests
+//
+// Created by Brent Simmons on 10/27/26.
+//
+
+import Foundation
+import Testing
+@testable import Images
+
+@MainActor @Suite struct ThumbnailTaskQueueTests {
+
+ @Test func oldestWaitingDownloadIsDroppedAndNewestGoesFirst() async {
+ let queue = ThumbnailTaskQueue(maximumRunningCount: 1, maximumWaitingCount: 2)
+ #expect(await queue.waitForTurn(key: "running") == .start)
+
+ let oldest = await startWaitingTask(queue: queue, key: "oldest")
+ let middle = await startWaitingTask(queue: queue, key: "middle")
+ let newest = Task { await queue.waitForTurn(key: "newest") }
+
+ // Waiting for the drop also means the newest task is in the queue.
+ #expect(await oldest.value == .dropped)
+
+ queue.taskDidFinish()
+ #expect(await newest.value == .start)
+ queue.taskDidFinish()
+ #expect(await middle.value == .start)
+ }
+
+ @Test func prioritizedTaskGoesAheadOfNewerTask() async {
+ let queue = ThumbnailTaskQueue(maximumRunningCount: 1, maximumWaitingCount: 10)
+ #expect(await queue.waitForTurn(key: "running") == .start)
+
+ let older = await startWaitingTask(queue: queue, key: "older")
+ let newer = await startWaitingTask(queue: queue, key: "newer")
+
+ queue.prioritize(key: "older")
+ queue.taskDidFinish()
+ #expect(await older.value == .start)
+ queue.taskDidFinish()
+ #expect(await newer.value == .start)
+ }
+
+ @Test func articleViewImageStartsWithoutWaitingForASlot() async {
+ let queue = ThumbnailTaskQueue(maximumRunningCount: 1, maximumWaitingCount: 10)
+ #expect(await queue.waitForTurn(key: "running") == .start)
+
+ let articleImage = await startWaitingTask(queue: queue, key: "articleImage")
+
+ // Starts while the running download still holds the only slot.
+ queue.startNow(key: "articleImage")
+ #expect(await articleImage.value == .startNow)
+ }
+
+ @Test func downloadsFromSlowHostLeaveSlotsForOtherHosts() async {
+ let slowHost = "slow.example.com"
+ let fastHost = "fast.example.com"
+ let queue = ThumbnailTaskQueue(maximumRunningCount: 2, maximumWaitingCount: 10, maximumRunningCountPerGroup: 1)
+ #expect(await queue.waitForTurn(key: "slow1", group: slowHost) == .start)
+ let slow2 = await startWaitingTask(queue: queue, key: "slow2", group: slowHost)
+
+ // Starts even though slow2 is waiting, since slow2’s host is at its limit.
+ #expect(await queue.waitForTurn(key: "fast1", group: fastHost) == .start)
+
+ let fast2 = await startWaitingTask(queue: queue, key: "fast2", group: fastHost)
+ let slow3 = await startWaitingTask(queue: queue, key: "slow3", group: slowHost)
+
+ // slow3 is the newest, but its host is still at its limit.
+ queue.taskDidFinish(group: fastHost)
+ #expect(await fast2.value == .start)
+
+ queue.taskDidFinish(group: slowHost)
+ #expect(await slow3.value == .start)
+
+ queue.taskDidFinish(group: slowHost)
+ #expect(await slow2.value == .start)
+ }
+}
+
+private extension ThumbnailTaskQueueTests {
+
+ /// Returns once the task is in the queue, so the order tasks are queued in doesn’t depend on scheduling.
+ func startWaitingTask(queue: ThumbnailTaskQueue, key: String, group: String? = nil) async -> Task {
+ let waitingCount = queue.waitingCount
+ let task = Task { await queue.waitForTurn(key: key, group: group) }
+ while queue.waitingCount == waitingCount {
+ await Task.yield()
+ }
+ return task
+ }
+}
diff --git a/Modules/NewsBlur/Package.swift b/Modules/NewsBlur/Package.swift
index 8259306e9..ebb83909f 100644
--- a/Modules/NewsBlur/Package.swift
+++ b/Modules/NewsBlur/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
let package = Package(
name: "NewsBlur",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(
name: "NewsBlur",
diff --git a/Modules/NewsBlur/Sources/NewsBlur/Models/NewsBlurStory.swift b/Modules/NewsBlur/Sources/NewsBlur/Models/NewsBlurStory.swift
index b6c603734..5a6432507 100644
--- a/Modules/NewsBlur/Sources/NewsBlur/Models/NewsBlurStory.swift
+++ b/Modules/NewsBlur/Sources/NewsBlur/Models/NewsBlurStory.swift
@@ -22,8 +22,18 @@ public struct NewsBlurStoriesResponse: Decodable, Sendable {
public let url: String?
public let authorName: String?
public let contentHTML: String?
+ /// The secure (proxied) copy of the first image, else the image itself.
public var imageURL: String? {
- return imageURLs?.first?.value
+ guard let firstImageURL = imageURLs?.first else {
+ return nil
+ }
+ return secureImageURLs?[firstImageURL] ?? firstImageURL
+ }
+ public var thumbnailURL: String? {
+ guard let firstImageURL = imageURLs?.first else {
+ return nil
+ }
+ return secureImageThumbnails?[firstImageURL]
}
public var tags: [String]?
public var datePublished: Date? {
@@ -31,7 +41,10 @@ public struct NewsBlurStoriesResponse: Decodable, Sendable {
return Date(timeIntervalSince1970: interval)
}
- private var imageURLs: [String: String]?
+ /// In story order. The secure dictionaries are keyed by these URLs.
+ private var imageURLs: [String]?
+ private var secureImageURLs: [String: String]?
+ private var secureImageThumbnails: [String: String]?
private var publishedTimestamp: String
}
}
@@ -50,7 +63,9 @@ extension NewsBlurStoriesResponse.Story {
case url = "story_permalink"
case authorName = "story_authors"
case contentHTML = "story_content"
- case imageURLs = "secure_image_urls"
+ case imageURLs = "image_urls"
+ case secureImageURLs = "secure_image_urls"
+ case secureImageThumbnails = "secure_image_thumbnails"
case tags = "story_tags"
case publishedTimestamp = "story_timestamp"
}
diff --git a/Modules/NewsBlur/Sources/NewsBlur/NewsBlurAPICaller.swift b/Modules/NewsBlur/Sources/NewsBlur/NewsBlurAPICaller.swift
index 728132874..a8dd68ac2 100644
--- a/Modules/NewsBlur/Sources/NewsBlur/NewsBlurAPICaller.swift
+++ b/Modules/NewsBlur/Sources/NewsBlur/NewsBlurAPICaller.swift
@@ -7,7 +7,7 @@
//
import Foundation
-import os
+import Synchronization
import RSWeb
import Secrets
@@ -17,13 +17,13 @@ public final class NewsBlurAPICaller: Sendable {
let baseURL = URL(string: "https://www.newsblur.com/")!
let session = URLSession.makeWebserviceSession()
- private let suspendedLock = OSAllocatedUnfairLock(initialState: false)
+ private let suspendedLock = Mutex(false)
var suspended: Bool {
get { suspendedLock.withLock { $0 }}
set { suspendedLock.withLock { $0 = newValue }}
}
- private let credentialsLock = OSAllocatedUnfairLock(initialState: nil)
+ private let credentialsLock = Mutex(nil)
public var credentials: Credentials? {
get { credentialsLock.withLock { $0 }}
set { credentialsLock.withLock { $0 = newValue }}
diff --git a/Modules/NewsBlur/Tests/NewsBlurTests/NewsBlurStoryTests.swift b/Modules/NewsBlur/Tests/NewsBlurTests/NewsBlurStoryTests.swift
new file mode 100644
index 000000000..c6b4274f0
--- /dev/null
+++ b/Modules/NewsBlur/Tests/NewsBlurTests/NewsBlurStoryTests.swift
@@ -0,0 +1,42 @@
+//
+// NewsBlurStoryTests.swift
+// NewsBlurTests
+//
+// Created by Brent Simmons on 10/23/26.
+//
+
+import Foundation
+import Testing
+@testable import NewsBlur
+
+struct NewsBlurStoryTests {
+
+ @Test func firstImageIsChosen() throws {
+ let json = """
+ {
+ "story_hash": "6:a1b2c3",
+ "story_feed_id": 6,
+ "story_timestamp": "1761235200",
+ "image_urls": [
+ "http://example.com/first.jpg",
+ "http://example.com/second.jpg",
+ "http://example.com/third.jpg"
+ ],
+ "secure_image_urls": {
+ "http://example.com/third.jpg": "https://imageproxy.newsblur.com/third",
+ "http://example.com/second.jpg": "https://imageproxy.newsblur.com/second",
+ "http://example.com/first.jpg": "https://imageproxy.newsblur.com/first"
+ },
+ "secure_image_thumbnails": {
+ "http://example.com/third.jpg": "https://imageproxy.newsblur.com/192/third",
+ "http://example.com/second.jpg": "https://imageproxy.newsblur.com/192/second",
+ "http://example.com/first.jpg": "https://imageproxy.newsblur.com/192/first"
+ }
+ }
+ """
+ let story = try JSONDecoder().decode(NewsBlurStory.self, from: Data(json.utf8))
+
+ #expect(story.imageURL == "https://imageproxy.newsblur.com/first")
+ #expect(story.thumbnailURL == "https://imageproxy.newsblur.com/192/first")
+ }
+}
diff --git a/Modules/RSCore/Package.swift b/Modules/RSCore/Package.swift
index 9c6ccd945..dd54eb275 100644
--- a/Modules/RSCore/Package.swift
+++ b/Modules/RSCore/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
let package = Package(
name: "RSCore",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(name: "RSCore", type: .dynamic, targets: ["RSCore"]),
.library(name: "RSCoreObjC", type: .dynamic, targets: ["RSCoreObjC"]),
diff --git a/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift b/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift
index ad214c411..bd55cc11e 100644
--- a/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift
+++ b/Modules/RSCore/Sources/RSCore/AppKit/NSTableView+RSCore.swift
@@ -34,14 +34,32 @@ public extension NSTableView {
}
/// The part of the document the user can actually see. documentVisibleRect includes
- /// the area under the toolbar, and under the sidebar on macOS 26.
+ /// the area under the toolbar, under the sidebar on macOS 26, and under the header view.
private var unobscuredDocumentRect: NSRect? {
guard let scrollView = self.enclosingScrollView else {
return nil
}
let contentInsets = scrollView.contentInsets
let documentVisibleRect = scrollView.documentVisibleRect
- return NSRect(x: documentVisibleRect.minX + contentInsets.left, y: documentVisibleRect.minY + contentInsets.top, width: documentVisibleRect.width - contentInsets.left - contentInsets.right, height: documentVisibleRect.height - contentInsets.top - contentInsets.bottom)
+ var rect = NSRect(x: documentVisibleRect.minX + contentInsets.left, y: documentVisibleRect.minY + contentInsets.top, width: documentVisibleRect.width - contentInsets.left - contentInsets.right, height: documentVisibleRect.height - contentInsets.top - contentInsets.bottom)
+
+ // The header floats over the clip view but isn’t part of contentInsets.
+ if let headerView, headerView.window != nil {
+ let headerBottom = convert(headerView.bounds, from: headerView).maxY
+ if headerBottom > rect.minY {
+ rect.size.height = max(0, rect.maxY - headerBottom)
+ rect.origin.y = headerBottom
+ }
+ }
+
+ return rect
+ }
+
+ func isRowFullyVisible(_ row: Int) -> Bool {
+ guard let unobscuredDocumentRect else {
+ return false
+ }
+ return unobscuredDocumentRect.contains(rect(ofRow: row))
}
func scrollTo(row: Int, extraHeight: Int = 150) {
@@ -49,15 +67,19 @@ public extension NSTableView {
return
}
- let r = rect(ofRow: row)
- if unobscuredDocumentRect.contains(r) {
+ if isRowFullyVisible(row) {
return
}
- // Center the row in the unobscured area, which starts contentInsets.top below the clip view’s origin.
+ let r = rect(ofRow: row)
+ // Center the row in the unobscured area, which starts obscuredTop below the clip view’s origin.
+ let obscuredTop = unobscuredDocumentRect.minY - scrollView.documentVisibleRect.minY
let rMidY = r.midY
+ // extraHeight shifts the row up from center — cap it so the row stays below the header in short tables.
+ let maximumExtraHeight = max(0, floor((unobscuredDocumentRect.size.height - r.height) / 2.0))
+ let clampedExtraHeight = min(CGFloat(extraHeight), maximumExtraHeight)
var scrollPoint = NSPoint.zero
- scrollPoint.y = floor(rMidY - (unobscuredDocumentRect.size.height / 2.0) - scrollView.contentInsets.top) + CGFloat(extraHeight)
+ scrollPoint.y = floor(rMidY - (unobscuredDocumentRect.size.height / 2.0) - obscuredTop) + clampedExtraHeight
let clipView = scrollView.contentView
@@ -67,14 +89,26 @@ public extension NSTableView {
clipView.animator().bounds = clipView.constrainBoundsRect(rClipView)
}
- func scrollToRowIfNotVisible(_ row: Int) {
- if let followingRow = rowView(atRow: row, makeIfNecessary: false) {
- if !(visibleRowViews()?.contains(followingRow) ?? false) {
- scrollTo(row: row, extraHeight: 0)
- }
- } else {
- scrollTo(row: row, extraHeight: 0)
+ /// A row above the visible area scrolls down just far enough to show it.
+ /// A row below the visible area is centered, so the rows after it show too.
+ func scrollRowFullyIntoView(_ row: Int) {
+ guard let scrollView = self.enclosingScrollView, let unobscuredDocumentRect else {
+ return
}
+
+ let r = rect(ofRow: row)
+ if r.maxY > unobscuredDocumentRect.maxY {
+ scrollTo(row: row, extraHeight: 0)
+ return
+ }
+ guard r.minY < unobscuredDocumentRect.minY else {
+ return
+ }
+
+ let clipView = scrollView.contentView
+ var bounds = clipView.bounds
+ bounds.origin.y += r.minY - unobscuredDocumentRect.minY
+ clipView.animator().bounds = clipView.constrainBoundsRect(bounds)
}
func visibleRowViews() -> [NSTableRowView]? {
diff --git a/Modules/RSCore/Sources/RSCore/BinaryDiskCache.swift b/Modules/RSCore/Sources/RSCore/BinaryDiskCache.swift
index aac68f50f..8f470a8a5 100644
--- a/Modules/RSCore/Sources/RSCore/BinaryDiskCache.swift
+++ b/Modules/RSCore/Sources/RSCore/BinaryDiskCache.swift
@@ -7,57 +7,46 @@
//
import Foundation
-import os
+/// Each key is its own file. Writes are atomic.
nonisolated public final class BinaryDiskCache: Sendable {
public let folder: String
- private let mutex = OSAllocatedUnfairLock(initialState: ())
public init(folder: String) {
self.folder = folder
}
public func data(forKey key: String) throws -> Data? {
- try mutex.withLock { _ in
- try _data(forKey: key)
- }
+ try _data(forKey: key)
}
public func setData(_ data: Data, forKey key: String) throws {
- try mutex.withLock { _ in
- try _setData(data, forKey: key)
- }
+ try _setData(data, forKey: key)
}
public func deleteData(forKey key: String) throws {
- try mutex.withLock { _ in
- try _deleteData(forKey: key)
- }
+ try _deleteData(forKey: key)
}
// Subscript doesn’t throw. Use when you can ignore errors.
public subscript(_ key: String) -> Data? {
get {
- mutex.withLock { _ in
- do {
- return try _data(forKey: key)
- } catch {}
- return nil
- }
+ do {
+ return try _data(forKey: key)
+ } catch {}
+ return nil
}
set {
- mutex.withLock { _ in
- if let data = newValue {
- do {
- try _setData(data, forKey: key)
- } catch {}
- } else {
- do {
- try _deleteData(forKey: key)
- } catch {}
- }
+ if let data = newValue {
+ do {
+ try _setData(data, forKey: key)
+ } catch {}
+ } else {
+ do {
+ try _deleteData(forKey: key)
+ } catch {}
}
}
}
@@ -67,12 +56,13 @@ nonisolated private extension BinaryDiskCache {
func _data(forKey key: String) throws -> Data? {
let url = urlForKey(key)
- return try Data(contentsOf: url)
+ // Mapped, so the bytes are file-backed pages the system can reclaim, not heap memory.
+ return try Data(contentsOf: url, options: .mappedIfSafe)
}
func _setData(_ data: Data, forKey key: String) throws {
let url = urlForKey(key)
- try data.write(to: url)
+ try data.write(to: url, options: .atomic)
}
func _deleteData(forKey key: String) throws {
diff --git a/Modules/RSCore/Sources/RSCore/Cache.swift b/Modules/RSCore/Sources/RSCore/Cache.swift
index bf027497d..2b1baf913 100644
--- a/Modules/RSCore/Sources/RSCore/Cache.swift
+++ b/Modules/RSCore/Sources/RSCore/Cache.swift
@@ -6,7 +6,7 @@
//
import Foundation
-import os
+import Synchronization
public protocol CacheRecord: Sendable {
var dateCreated: Date { get }
@@ -21,7 +21,7 @@ public final class Cache: Sendable {
var lastCleanupDate = Date()
var cache = [String: T]()
}
- private let stateLock = OSAllocatedUnfairLock(initialState: State())
+ private let stateLock = Mutex(State())
public init(timeToLive: TimeInterval, timeBetweenCleanups: TimeInterval) {
self.timeToLive = timeToLive
diff --git a/Modules/RSCore/Sources/RSCore/Geometry.swift b/Modules/RSCore/Sources/RSCore/Geometry.swift
index 912e945d7..bd8ad7d81 100644
--- a/Modules/RSCore/Sources/RSCore/Geometry.swift
+++ b/Modules/RSCore/Sources/RSCore/Geometry.swift
@@ -44,6 +44,18 @@ public extension CGRect {
func centered(in containerRect: CGRect) -> CGRect {
self.centeredHorizontally(in: self.centeredVertically(in: containerRect))
}
+
+ /// The largest rectangle with `size`’s aspect ratio that fits in this one, centered, in whole points.
+ /// This rectangle when `size` has no width or height.
+ func aspectFitRect(for size: CGSize) -> CGRect {
+ guard size.width > 0.0, size.height > 0.0 else {
+ return self
+ }
+ let scale = Swift.min(width / size.width, height / size.height)
+ let fittedWidth = (size.width * scale).rounded()
+ let fittedHeight = (size.height * scale).rounded()
+ return CGRect(x: minX + floor((width - fittedWidth) / 2.0), y: minY + floor((height - fittedHeight) / 2.0), width: fittedWidth, height: fittedHeight)
+ }
}
public extension Array where Element == CGRect {
diff --git a/Modules/RSCore/Sources/RSCore/MainThreadOperation.swift b/Modules/RSCore/Sources/RSCore/MainThreadOperation.swift
index 122107389..3b07e3f98 100644
--- a/Modules/RSCore/Sources/RSCore/MainThreadOperation.swift
+++ b/Modules/RSCore/Sources/RSCore/MainThreadOperation.swift
@@ -7,7 +7,7 @@
//
import Foundation
-import os
+import Synchronization
/// Code to be run by MainThreadOperationQueue on @MainActor.
///
@@ -31,7 +31,7 @@ import os
private struct State: Sendable {
var isCanceled = false
}
- private let state = OSAllocatedUnfairLock(initialState: State())
+ private let state = Mutex(State())
// Check this at appropriate times in case the operation has been canceled.
nonisolated public var isCanceled: Bool {
diff --git a/Modules/RSCore/Sources/RSCore/MemoryPressureMonitor.swift b/Modules/RSCore/Sources/RSCore/MemoryPressureMonitor.swift
deleted file mode 100644
index 7365671a8..000000000
--- a/Modules/RSCore/Sources/RSCore/MemoryPressureMonitor.swift
+++ /dev/null
@@ -1,32 +0,0 @@
-//
-// MemoryPressureMonitor.swift
-// RSCore
-//
-// Created by Brent Simmons on 3/7/26.
-//
-
-#if os(macOS)
-
-import Foundation
-import Dispatch
-
-/// Observes GCD memory pressure events on macOS.
-/// Posts `.lowMemory` on warn or critical.
-public final class MemoryPressureMonitor: Sendable {
- public static let shared = MemoryPressureMonitor()
-
- private let source: DispatchSourceMemoryPressure
-
- init() {
- source = DispatchSource.makeMemoryPressureSource(eventMask: [.warning, .critical], queue: .main)
- source.setEventHandler {
- AppNotification.postLowMemory()
- }
- }
-
- public func start() {
- source.activate()
- }
-}
-
-#endif
diff --git a/Modules/RSCore/Sources/RSCore/RSImage.swift b/Modules/RSCore/Sources/RSCore/RSImage.swift
index adc9795cd..69dc08fcc 100644
--- a/Modules/RSCore/Sources/RSCore/RSImage.swift
+++ b/Modules/RSCore/Sources/RSCore/RSImage.swift
@@ -132,44 +132,84 @@ public extension RSImage {
}
}
- /// Scales image data down to maxPixelSize and returns the result as PNG Data.
+ /// 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)? {
+ guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil), let largestFrame = largestFrame(in: imageSource) else {
+ return nil
+ }
+ return (width: largestFrame.width, height: largestFrame.height)
+ }
+
+ /// Index and pixel dimensions of the largest frame, read from the image header without decoding.
+ static func largestFrame(in imageSource: CGImageSource) -> (index: Int, width: Int, height: Int)? {
+ var largest: (index: Int, width: Int, height: Int)?
+
+ for i in 0.. 0, height > 0 else {
+ continue
+ }
+ if let largest, max(largest.width, largest.height) >= max(width, height) {
+ continue
+ }
+ largest = (index: i, width: width, height: height)
+ }
+
+ return largest
+ }
+
+ /// Scales image data down to maxPixelSize and returns the result encoded as PNG.
/// If the image is a single frame already at or below maxPixelSize, returns
/// the original data unchanged. For multi-image sources (like ICO), extracts
- /// the largest frame. Returns nil if the data can't be decoded as an image.
+ /// the largest frame. On the Mac, an image ImageIO can’t read, such as SVG, is rasterized
+ /// so its longer side is maxPixelSize. Returns nil if the data can't be decoded as an image.
static func scaledImageData(_ data: Data, maxPixelSize: Int) -> Data? {
- guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else {
+ guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil), let largestFrame = largestFrame(in: imageSource) else {
+#if os(macOS)
+ return rasterizedVectorImageData(data, maxPixelSize: maxPixelSize)
+#else
return nil
+#endif
}
let count = CGImageSourceGetCount(imageSource)
- guard count > 0 else {
- return nil
- }
-
- // Find the largest frame in the image source.
- var largestIndex = 0
- var largestWidth = 0
- var largestHeight = 0
- var largestMaxDimension = 0
-
- for i in 0.. largestMaxDimension {
- largestIndex = i
- largestWidth = width
- largestHeight = height
- largestMaxDimension = maxDimension
- }
- }
-
- guard largestMaxDimension > 0 else {
- return nil
- }
+ let largestIndex = largestFrame.index
+ let largestWidth = largestFrame.width
+ let largestHeight = largestFrame.height
+ let largestMaxDimension = max(largestWidth, largestHeight)
let needsResize = largestMaxDimension > maxPixelSize
let isMultiImage = count > 1
@@ -180,28 +220,20 @@ public extension RSImage {
return data
}
- // Either too large or multi-image — extract/resize to a single PNG.
+ // Either too large or multi-image — extract/resize to a single image.
// Always use CreateThumbnailAtIndex rather than CreateImageAtIndex,
// because the latter mishandles indexed-color ICO files (produces
// grayscale with a nil color space instead of correct RGB).
+ // FromImageAlways, since a JPEG’s embedded EXIF thumbnail is small and low quality.
let thumbnailSize = needsResize ? maxPixelSize : largestMaxDimension
let options: [CFString: Any] = [
kCGImageSourceCreateThumbnailWithTransform: true,
- kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceThumbnailMaxPixelSize: thumbnailSize
]
let cgImage = CGImageSourceCreateThumbnailAtIndex(imageSource, largestIndex, options as CFDictionary)
- guard let cgImage else {
- return nil
- }
-
- guard let mutableData = CFDataCreateMutable(nil, 0),
- let destination = CGImageDestinationCreateWithData(mutableData, UTType.png.identifier as CFString, 1, nil) else {
- return nil
- }
- CGImageDestinationAddImage(destination, cgImage, nil)
- guard CGImageDestinationFinalize(destination) else {
+ guard let cgImage, let scaledData = pngData(cgImage) else {
return nil
}
@@ -211,6 +243,48 @@ public extension RSImage {
RSImageLogger.info("Extracted largest frame (\(largestWidth, privacy: .public)x\(largestHeight, privacy: .public)) from multi-image source (\(count, privacy: .public) frames)")
}
- return mutableData as Data
+ return scaledData
}
}
+
+private extension RSImage {
+
+ static func pngData(_ cgImage: CGImage) -> Data? {
+ guard let mutableData = CFDataCreateMutable(nil, 0), let destination = CGImageDestinationCreateWithData(mutableData, UTType.png.identifier as CFString, 1, nil) else {
+ return nil
+ }
+ CGImageDestinationAddImage(destination, cgImage, nil)
+ guard CGImageDestinationFinalize(destination) else {
+ return nil
+ }
+ return mutableData as Data
+ }
+
+#if os(macOS)
+ static let rasterizedBitsPerComponent = 8
+
+ /// Draws a vector image, such as SVG, into a bitmap, so views don’t rasterize it on the main thread each time they draw.
+ static func rasterizedVectorImageData(_ data: Data, maxPixelSize: Int) -> Data? {
+ guard let image = NSImage(data: data), image.size.width > 0, image.size.height > 0 else {
+ return nil
+ }
+ let scale = CGFloat(maxPixelSize) / max(image.size.width, image.size.height)
+ let width = max(1, Int((image.size.width * scale).rounded()))
+ let height = max(1, Int((image.size.height * scale).rounded()))
+
+ guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB), let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: rasterizedBitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
+ return nil
+ }
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
+ image.draw(in: NSRect(x: 0, y: 0, width: width, height: height))
+ NSGraphicsContext.restoreGraphicsState()
+
+ guard let cgImage = context.makeImage(), let rasterizedData = pngData(cgImage) else {
+ return nil
+ }
+ RSImageLogger.info("Rasterized vector image at \(width, privacy: .public)x\(height, privacy: .public)")
+ return rasterizedData
+ }
+#endif
+}
diff --git a/Modules/RSCore/Sources/RSCore/String+PlainTextToHTML.swift b/Modules/RSCore/Sources/RSCore/String+PlainTextToHTML.swift
new file mode 100644
index 000000000..8e7e50b23
--- /dev/null
+++ b/Modules/RSCore/Sources/RSCore/String+PlainTextToHTML.swift
@@ -0,0 +1,64 @@
+//
+// String+PlainTextToHTML.swift
+// RSCore
+//
+// Created by Brent Simmons on 10/23/26.
+//
+
+import Foundation
+
+private let linkDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
+private let linkSchemes: Set = ["http", "https", "mailto"]
+
+public extension String {
+
+ /// HTML for plain text: escaped, with blank lines as paragraph breaks,
+ /// other line breaks as ` `, and URLs as links.
+ var convertingPlainTextToHTML: String {
+ let lines = replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")
+
+ var paragraphs = [String]()
+ var paragraphLines = [String]()
+ func endParagraph() {
+ if !paragraphLines.isEmpty {
+ paragraphs.append("" + paragraphLines.joined(separator: " \n") + "
")
+ paragraphLines.removeAll()
+ }
+ }
+
+ for line in lines {
+ if line.trimmingCharacters(in: .whitespaces).isEmpty {
+ endParagraph()
+ } else {
+ paragraphLines.append(Self.linkifiedEscapedLine(line))
+ }
+ }
+ endParagraph()
+
+ return paragraphs.joined(separator: "\n")
+ }
+}
+
+private extension String {
+
+ static func linkifiedEscapedLine(_ line: String) -> String {
+ guard let linkDetector else {
+ return line.escapingSpecialXMLCharacters
+ }
+
+ let nsLine = line as NSString
+ var html = ""
+ var location = 0
+ for match in linkDetector.matches(in: line, range: NSRange(location: 0, length: nsLine.length)) {
+ guard let url = match.url, let scheme = url.scheme?.lowercased(), linkSchemes.contains(scheme) else {
+ continue
+ }
+ html += nsLine.substring(with: NSRange(location: location, length: match.range.location - location)).escapingSpecialXMLCharacters
+ let linkText = nsLine.substring(with: match.range).escapingSpecialXMLCharacters
+ html += "\(linkText) "
+ location = match.range.location + match.range.length
+ }
+ html += nsLine.substring(from: location).escapingSpecialXMLCharacters
+ return html
+ }
+}
diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift
index 1b6064039..52843a36a 100644
--- a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift
+++ b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift
@@ -34,13 +34,6 @@ extension UICollectionView {
scrollToItem(at: indexPath, at: .centeredVertically, animated: animations.contains(.scroll))
}
- public func middleVisibleRow() -> IndexPath? {
- if indexPathsForVisibleItems.count > 2 {
- return indexPathsForVisibleItems[indexPathsForVisibleItems.count / 2]
- }
- return nil
- }
-
}
#endif
diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UITableView+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UITableView+RSCore.swift
index 7f8e46903..7e583749c 100644
--- a/Modules/RSCore/Sources/RSCore/UIKit/UITableView+RSCore.swift
+++ b/Modules/RSCore/Sources/RSCore/UIKit/UITableView+RSCore.swift
@@ -34,13 +34,6 @@ public extension UITableView {
let rect = rectForRow(at: indexPath)
return safeAreaLayoutGuide.layoutFrame.contains(rect)
}
-
- func middleVisibleRow() -> IndexPath? {
- if let visibleIndexPaths = indexPathsForRows(in: safeAreaLayoutGuide.layoutFrame), visibleIndexPaths.count > 2 {
- return visibleIndexPaths[visibleIndexPaths.count / 2]
- }
- return nil
- }
}
#endif
diff --git a/Modules/RSCore/Tests/RSCoreTests/GeometryTests.swift b/Modules/RSCore/Tests/RSCoreTests/GeometryTests.swift
new file mode 100644
index 000000000..cd4fec8a1
--- /dev/null
+++ b/Modules/RSCore/Tests/RSCoreTests/GeometryTests.swift
@@ -0,0 +1,19 @@
+//
+// GeometryTests.swift
+// RSCoreTests
+//
+// Created by Brent Simmons on 11/5/26.
+//
+
+import CoreGraphics
+import Testing
+import RSCore
+
+@Suite struct GeometryTests {
+
+ @Test func aspectFitRectCentersALandscapeImageInAWiderRect() {
+ // A large thumbnail’s rect and a 3:2 image: 180 tall, 270 wide, centered.
+ let rect = CGRect(x: 20, y: 40, width: 400, height: 180)
+ #expect(rect.aspectFitRect(for: CGSize(width: 1500, height: 1000)) == CGRect(x: 85, y: 40, width: 270, height: 180))
+ }
+}
diff --git a/Modules/RSCore/Tests/RSCoreTests/PlainTextToHTMLTests.swift b/Modules/RSCore/Tests/RSCoreTests/PlainTextToHTMLTests.swift
new file mode 100644
index 000000000..585edbcce
--- /dev/null
+++ b/Modules/RSCore/Tests/RSCoreTests/PlainTextToHTMLTests.swift
@@ -0,0 +1,32 @@
+//
+// PlainTextToHTMLTests.swift
+// RSCoreTests
+//
+// Created by Brent Simmons on 10/23/26.
+//
+
+import Foundation
+import Testing
+import RSCore
+
+@Suite struct PlainTextToHTMLTests {
+
+ @Test func youTubeDescription() {
+ let text = """
+ HomeView recognizes up to six people & keeps in the loop.
+
+ Learn more and shop Apple HomeView: https://apple.co/4s4jhly
+ Collect 200 by Collect 200: https://music.apple/collect-200
+
+
+ Siri AI is available in beta.
+ """
+ let expected = """
+ HomeView recognizes up to six people & keeps <everyone> in the loop.
+ Learn more and shop Apple HomeView: https://apple.co/4s4jhly
+ Collect 200 by Collect 200: https://music.apple/collect-200
+ Siri AI is available in beta.
+ """
+ #expect(text.convertingPlainTextToHTML == expected)
+ }
+}
diff --git a/Modules/RSCore/Tests/RSCoreTests/ScaledImageDataTests.swift b/Modules/RSCore/Tests/RSCoreTests/ScaledImageDataTests.swift
new file mode 100644
index 000000000..33229b0de
--- /dev/null
+++ b/Modules/RSCore/Tests/RSCoreTests/ScaledImageDataTests.swift
@@ -0,0 +1,84 @@
+//
+// ScaledImageDataTests.swift
+// RSCore
+//
+// Created by Brent Simmons on 10/25/26.
+//
+
+import Foundation
+import Testing
+import CoreGraphics
+import ImageIO
+import UniformTypeIdentifiers
+@testable import RSCore
+
+@Suite struct ScaledImageDataTests {
+
+ @Test func largeImageIsResizedToPNG() throws {
+ let data = try #require(pngData(width: 2000, height: 1000))
+
+ let scaledData = try #require(RSImage.scaledImageData(data, maxPixelSize: 512))
+
+ #expect(imageType(scaledData) == UTType.png.identifier)
+ #expect(RSImage.largestFramePixelSize(scaledData)?.width == 512)
+ #expect(RSImage.largestFramePixelSize(scaledData)?.height == 256)
+ }
+
+ @Test func jpegIsScaledFromFullImageNotEmbeddedThumbnail() throws {
+ let data = try #require(imageData(width: 2000, height: 1500, type: UTType.jpeg, embedsThumbnail: true))
+
+ let scaledData = try #require(RSImage.scaledImageData(data, maxPixelSize: 288))
+
+ #expect(RSImage.largestFramePixelSize(scaledData)?.width == 288)
+ #expect(RSImage.largestFramePixelSize(scaledData)?.height == 216)
+ }
+
+#if os(macOS)
+ @Test func svgIsRasterizedToPNG() throws {
+ let scaledData = try #require(RSImage.scaledImageData(svgData, maxPixelSize: 64))
+
+ #expect(imageType(scaledData) == UTType.png.identifier)
+ #expect(RSImage.largestFramePixelSize(scaledData)?.width == 64)
+ #expect(RSImage.largestFramePixelSize(scaledData)?.height == 32)
+ }
+
+ @Test func svgRasterizingIsDeterministic() throws {
+ let scaledData = try #require(RSImage.scaledImageData(svgData, maxPixelSize: 64))
+ let scaledAgainData = try #require(RSImage.scaledImageData(svgData, maxPixelSize: 64))
+
+ #expect(scaledData == scaledAgainData)
+ }
+#endif
+}
+
+// MARK: - Helpers
+
+private let svgData = Data(##" "##.utf8)
+
+private func pngData(width: Int, height: Int) -> Data? {
+ imageData(width: width, height: height, type: UTType.png, embedsThumbnail: false)
+}
+
+private func imageData(width: Int, height: Int, type: UTType, embedsThumbnail: Bool) -> Data? {
+ guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else {
+ return nil
+ }
+ context.setFillColor(red: 0.2, green: 0.4, blue: 0.6, alpha: 1)
+ context.fill(CGRect(x: 0, y: 0, width: width, height: height))
+ guard let cgImage = context.makeImage(), let mutableData = CFDataCreateMutable(nil, 0), let destination = CGImageDestinationCreateWithData(mutableData, type.identifier as CFString, 1, nil) else {
+ return nil
+ }
+ let properties = [kCGImageDestinationEmbedThumbnail: embedsThumbnail] as CFDictionary
+ CGImageDestinationAddImage(destination, cgImage, properties)
+ guard CGImageDestinationFinalize(destination) else {
+ return nil
+ }
+ return mutableData as Data
+}
+
+private func imageType(_ data: Data) -> String? {
+ guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else {
+ return nil
+ }
+ return CGImageSourceGetType(imageSource) as String?
+}
diff --git a/Modules/RSDatabase/Package.swift b/Modules/RSDatabase/Package.swift
index 95f657adb..9de622d70 100644
--- a/Modules/RSDatabase/Package.swift
+++ b/Modules/RSDatabase/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
let package = Package(
name: "RSDatabase",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(
name: "RSDatabase",
diff --git a/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift b/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift
index d05469118..ac6b03426 100644
--- a/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift
+++ b/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift
@@ -11,33 +11,30 @@ import os
import SQLite3
import RSDatabaseObjC
+/// DELETE avoids the extra -wal and -shm files. WAL makes frequent small writes faster.
+public enum JournalMode: String, Sendable {
+ case delete = "DELETE"
+ case wal = "WAL"
+}
+
/// Manage a serial queue and a SQLite database.
public final class DatabaseQueue: Sendable {
- private struct State: @unchecked Sendable {
- var isCallingDatabase = false
- let database: FMDatabase
- init(_ database: FMDatabase) {
- self.database = database
- }
- }
-
- private let state: OSAllocatedUnfairLock
+ nonisolated(unsafe) private let database: FMDatabase // Used on serial dispatch queue only
private let databasePath: String
private let serialDispatchQueue: DispatchQueue
private static let logger = Logger(subsystem: logSubsystem, category: "DatabaseQueue")
- public init(databasePath: String) {
+ public init(databasePath: String, journalMode: JournalMode = .delete) {
Self.logger.debug("DatabaseQueue: creating with database path \(databasePath)")
self.serialDispatchQueue = DispatchQueue(label: "DatabaseQueue (Serial) - \(databasePath)")
self.databasePath = databasePath
- let database = FMDatabase(path: databasePath)!
- self.state = OSAllocatedUnfairLock(initialState: State(database))
+ self.database = FMDatabase(path: databasePath)!
- self.state.withLock { openDatabase($0.database) }
+ openDatabase(database, journalMode: journalMode)
}
// MARK: - Make Database Calls
@@ -48,18 +45,14 @@ public final class DatabaseQueue: Sendable {
/// scheduled on the queue. Use sparingly — prefer async versions.
public func runInDatabaseSync(_ databaseBlock: DatabaseBlock) {
serialDispatchQueue.sync {
- self.state.withLock { state in
- self._runInDatabase(&state, databaseBlock, false)
- }
+ self._runInDatabase(databaseBlock, false)
}
}
/// Run a DatabaseBlock asynchronously.
public func runInDatabase(_ databaseBlock: @escaping DatabaseBlock) {
serialDispatchQueue.async {
- self.state.withLock { state in
- self._runInDatabase(&state, databaseBlock, false)
- }
+ self._runInDatabase(databaseBlock, false)
}
}
@@ -69,9 +62,7 @@ public final class DatabaseQueue: Sendable {
/// prefer the async `runInTransaction` instead.
public func runInTransactionSync(_ databaseBlock: @escaping DatabaseBlock) {
serialDispatchQueue.sync {
- self.state.withLock { state in
- self._runInDatabase(&state, databaseBlock, true)
- }
+ self._runInDatabase(databaseBlock, true)
}
}
@@ -79,9 +70,7 @@ public final class DatabaseQueue: Sendable {
/// Transactions help performance significantly when updating the database.
public func runInTransaction(_ databaseBlock: @escaping DatabaseBlock) {
serialDispatchQueue.async {
- self.state.withLock { state in
- self._runInDatabase(&state, databaseBlock, true)
- }
+ self._runInDatabase(databaseBlock, true)
}
}
@@ -112,34 +101,38 @@ public final class DatabaseQueue: Sendable {
}
}
}
+
+ /// Copy the WAL into the database and truncate the -wal file.
+ /// For WAL-mode databases, this takes the place of vacuum().
+ public func checkpoint() async {
+ await withCheckedContinuation { continuation in
+ runInDatabase { database in
+ database.checkpoint()
+ continuation.resume()
+ }
+ }
+ }
}
private extension DatabaseQueue {
- private func _runInDatabase(_ state: inout State, _ databaseBlock: DatabaseBlock, _ useTransaction: Bool) {
- precondition(!state.isCallingDatabase)
-
- state.isCallingDatabase = true
- defer {
- state.isCallingDatabase = false
- }
+ private func _runInDatabase(_ databaseBlock: DatabaseBlock, _ useTransaction: Bool) {
+ dispatchPrecondition(condition: .onQueue(serialDispatchQueue))
autoreleasepool {
if useTransaction {
- state.database.beginTransaction()
+ database.beginTransaction()
}
- databaseBlock(state.database)
+ databaseBlock(database)
if useTransaction {
- state.database.commit()
+ database.commit()
}
}
}
- func openDatabase(_ database: FMDatabase) {
+ func openDatabase(_ database: FMDatabase, journalMode: JournalMode) {
database.open()
- // All databases are single-connection and serialized — WAL gains us nothing
- // and produces extra -wal/-shm files that bloat on disk.
- database.executeStatements("PRAGMA journal_mode = DELETE;")
+ database.executeStatements("PRAGMA journal_mode = \(journalMode.rawValue);")
database.executeStatements("PRAGMA synchronous = 1;")
database.setShouldCacheStatements(true)
}
diff --git a/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift b/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift
index 5b3de7b2c..33f52c1e0 100644
--- a/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift
+++ b/Modules/RSDatabase/Sources/RSDatabase/FMDatabase+Extras.swift
@@ -15,8 +15,6 @@ public extension FMDatabase {
let database = FMDatabase(path: path)!
database.open()
- // All databases are single-connection and serialized — WAL gains us nothing
- // and produces extra -wal/-shm files that bloat on disk.
database.executeStatements("PRAGMA journal_mode = DELETE;")
database.executeStatements("PRAGMA synchronous = 1;")
database.setShouldCacheStatements(true)
@@ -50,6 +48,15 @@ public extension FMDatabase {
Self.logger.debug("VACUUM \(path, privacy: .public) took \(duration, format: .fixed(precision: 4), privacy: .public) seconds")
}
+ /// Copy the WAL into the database and truncate the -wal file.
+ func checkpoint() {
+ let path = databasePath() ?? "unknown"
+ let start = Date()
+ executeStatements("PRAGMA wal_checkpoint(TRUNCATE);")
+ let duration = Date().timeIntervalSince(start)
+ Self.logger.debug("Checkpoint \(path, privacy: .public) took \(duration, format: .fixed(precision: 4), privacy: .public) seconds")
+ }
+
/// Vacuum if at least `daysBetweenVacuums` have passed since last time.
/// The last vacuum date is stored in the database.
func vacuumIfNeeded(daysBetweenVacuums: Int = RSDatabaseInfoTable.defaultDaysBetweenVacuums) {
diff --git a/Modules/RSParser/Package.swift b/Modules/RSParser/Package.swift
index 316578a9d..8b397d8b6 100644
--- a/Modules/RSParser/Package.swift
+++ b/Modules/RSParser/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
let package = Package(
name: "RSParser",
- platforms: [.macOS(.v15), .iOS(.v17)],
+ platforms: [.macOS(.v15), .iOS(.v18)],
products: [
.library(
name: "RSParser",
diff --git a/Modules/RSParser/Sources/RSParser/Feeds/JSON/JSONFeedParser.swift b/Modules/RSParser/Sources/RSParser/Feeds/JSON/JSONFeedParser.swift
index 7e04924b1..c33dff871 100644
--- a/Modules/RSParser/Sources/RSParser/Feeds/JSON/JSONFeedParser.swift
+++ b/Modules/RSParser/Sources/RSParser/Feeds/JSON/JSONFeedParser.swift
@@ -166,7 +166,7 @@ private extension JSONFeedParser {
}
let attachments = parseAttachments(itemDictionary)
- return ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedURL, url: url, externalURL: externalURL, title: title, language: language, contentHTML: contentHTML, contentText: contentText, markdown: nil, summary: summary, imageURL: imageURL, bannerImageURL: bannerImageURL, datePublished: datePublished, dateModified: dateModified, authors: authors, tags: tags, attachments: attachments)
+ return ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedURL, url: url, externalURL: externalURL, title: title, language: language, contentHTML: contentHTML, contentText: contentText, markdown: nil, summary: summary, imageURL: imageURL, thumbnailURL: nil, bannerImageURL: bannerImageURL, datePublished: datePublished, dateModified: dateModified, authors: authors, tags: tags, attachments: attachments)
}
static func parseTitle(_ itemDictionary: JSONDictionary, _ feedURL: String) -> String? {
@@ -221,12 +221,12 @@ private extension JSONFeedParser {
return DateParser.date(from: dateString)
}
- static func parseAttachments(_ itemDictionary: JSONDictionary) -> Set? {
+ static func parseAttachments(_ itemDictionary: JSONDictionary) -> [ParsedAttachment]? {
guard let attachmentsArray = itemDictionary[Key.attachments] as? JSONArray else {
return nil
}
- return Set(attachmentsArray.compactMap { parseAttachment($0) })
+ return attachmentsArray.compactMap { parseAttachment($0) }
}
static func parseAttachment(_ attachmentObject: JSONDictionary) -> ParsedAttachment? {
@@ -234,14 +234,12 @@ private extension JSONFeedParser {
guard let url = attachmentObject[Key.url] as? String else {
return nil
}
- guard let mimeType = attachmentObject[Key.mimeType] as? String else {
- return nil
- }
+ let mimeType = attachmentObject[Key.mimeType] as? String
let title = attachmentObject[Key.title] as? String
let sizeInBytes = attachmentObject[Key.sizeInBytes] as? Int
let durationInSeconds = attachmentObject[Key.durationInSeconds] as? Int
- return ParsedAttachment(url: url, mimeType: mimeType, title: title, sizeInBytes: sizeInBytes, durationInSeconds: durationInSeconds)
+ return ParsedAttachment(url: url, mimeType: mimeType, title: title, sizeInBytes: sizeInBytes, durationInSeconds: durationInSeconds, width: nil, height: nil, medium: nil)
}
}
diff --git a/Modules/RSParser/Sources/RSParser/Feeds/JSON/RSSInJSONParser.swift b/Modules/RSParser/Sources/RSParser/Feeds/JSON/RSSInJSONParser.swift
index 19b995ee4..9dd8b2558 100644
--- a/Modules/RSParser/Sources/RSParser/Feeds/JSON/RSSInJSONParser.swift
+++ b/Modules/RSParser/Sources/RSParser/Feeds/JSON/RSSInJSONParser.swift
@@ -130,7 +130,7 @@ private extension RSSInJSONParser {
}
if let uniqueID = uniqueID {
- return ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedURL, url: nil, externalURL: externalURL, title: title, language: nil, contentHTML: contentHTML, contentText: contentText, markdown: nil, summary: nil, imageURL: nil, bannerImageURL: nil, datePublished: datePublished, dateModified: nil, authors: authors, tags: tags, attachments: attachments)
+ return ParsedItem(syncServiceID: nil, uniqueID: uniqueID, feedURL: feedURL, url: nil, externalURL: externalURL, title: title, language: nil, contentHTML: contentHTML, contentText: contentText, markdown: nil, summary: nil, imageURL: nil, thumbnailURL: nil, bannerImageURL: nil, datePublished: datePublished, dateModified: nil, authors: authors, tags: tags, attachments: attachments)
}
return nil
}
@@ -157,7 +157,7 @@ private extension RSSInJSONParser {
return nil
}
- static func parseAttachments(_ itemDictionary: JSONDictionary) -> Set? {
+ static func parseAttachments(_ itemDictionary: JSONDictionary) -> [ParsedAttachment]? {
guard let enclosureObject = itemDictionary["enclosure"] as? JSONDictionary else {
return nil
@@ -174,8 +174,8 @@ private extension RSSInJSONParser {
}
let type = enclosureObject["type"] as? String
- if let attachment = ParsedAttachment(url: attachmentURL, mimeType: type, title: nil, sizeInBytes: attachmentSize, durationInSeconds: nil) {
- return Set([attachment])
+ if let attachment = ParsedAttachment(url: attachmentURL, mimeType: type, title: nil, sizeInBytes: attachmentSize, durationInSeconds: nil, width: nil, height: nil, medium: nil) {
+ return [attachment]
}
return nil
}
diff --git a/Modules/RSParser/Sources/RSParser/Feeds/ParsedAttachment.swift b/Modules/RSParser/Sources/RSParser/Feeds/ParsedAttachment.swift
index f1f0eda33..54bf1f5d7 100644
--- a/Modules/RSParser/Sources/RSParser/Feeds/ParsedAttachment.swift
+++ b/Modules/RSParser/Sources/RSParser/Feeds/ParsedAttachment.swift
@@ -9,13 +9,26 @@
import Foundation
public struct ParsedAttachment: Hashable, Sendable {
+
+ /// Media RSS `medium` attribute.
+ public enum Medium: String, Sendable {
+ case image
+ case audio
+ case video
+ case document
+ case executable
+ }
+
public let url: String
public let mimeType: String?
public let title: String?
public let sizeInBytes: Int?
public let durationInSeconds: Int?
+ public let width: Int?
+ public let height: Int?
+ public let medium: Medium?
- public init?(url: String, mimeType: String?, title: String?, sizeInBytes: Int?, durationInSeconds: Int?) {
+ public init?(url: String, mimeType: String?, title: String?, sizeInBytes: Int?, durationInSeconds: Int?, width: Int?, height: Int?, medium: Medium?) {
if url.isEmpty {
return nil
}
@@ -25,6 +38,9 @@ public struct ParsedAttachment: Hashable, Sendable {
self.title = title
self.sizeInBytes = sizeInBytes
self.durationInSeconds = durationInSeconds
+ self.width = width
+ self.height = height
+ self.medium = medium
}
// MARK: - Hashable
@@ -33,3 +49,48 @@ public struct ParsedAttachment: Hashable, Sendable {
hasher.combine(url)
}
}
+
+// MARK: - Duration
+
+extension ParsedAttachment {
+
+ private static let maximumDurationComponentCount = 3 // 1:00:00
+
+ /// Parses plain seconds (`3600`, `3600.5`) and clock forms (`1:00:00`, `59:30`).
+ public static func durationInSeconds(_ s: String?) -> Int? {
+ guard let s else {
+ return nil
+ }
+ let components = s.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: ":", omittingEmptySubsequences: false)
+ guard components.count <= maximumDurationComponentCount else {
+ return nil
+ }
+
+ var seconds = 0.0
+ for component in components {
+ guard let value = Double(component), value.isFinite, value >= 0 else {
+ return nil
+ }
+ seconds = seconds * 60 + value
+ }
+
+ guard let wholeSeconds = Int(exactly: seconds.rounded(.down)), wholeSeconds > 0 else {
+ return nil
+ }
+ return wholeSeconds
+ }
+}
+
+// MARK: - Merging
+
+extension ParsedAttachment {
+
+ /// Copy with each nil property filled in from `other`.
+ func filledIn(from other: ParsedAttachment) -> ParsedAttachment {
+ ParsedAttachment(url: url, mimeType: mimeType ?? other.mimeType, title: title ?? other.title, sizeInBytes: sizeInBytes ?? other.sizeInBytes, durationInSeconds: durationInSeconds ?? other.durationInSeconds, width: width ?? other.width, height: height ?? other.height, medium: medium ?? other.medium) ?? self
+ }
+
+ func withDurationInSeconds(_ durationInSeconds: Int) -> ParsedAttachment {
+ ParsedAttachment(url: url, mimeType: mimeType, title: title, sizeInBytes: sizeInBytes, durationInSeconds: durationInSeconds, width: width, height: height, medium: medium) ?? self
+ }
+}
diff --git a/Modules/RSParser/Sources/RSParser/Feeds/ParsedItem.swift b/Modules/RSParser/Sources/RSParser/Feeds/ParsedItem.swift
index 876130919..4d54d53fe 100644
--- a/Modules/RSParser/Sources/RSParser/Feeds/ParsedItem.swift
+++ b/Modules/RSParser/Sources/RSParser/Feeds/ParsedItem.swift
@@ -22,12 +22,13 @@ public struct ParsedItem: Hashable, Sendable {
public let markdown: String?
public let summary: String?
public let imageURL: String?
+ public let thumbnailURL: String?
public let bannerImageURL: String?
public let datePublished: Date?
public let dateModified: Date?
public let authors: Set?
public let tags: Set?
- public let attachments: Set?
+ public let attachments: [ParsedAttachment]?
public init(syncServiceID: String?,
uniqueID: String,
@@ -41,12 +42,13 @@ public struct ParsedItem: Hashable, Sendable {
markdown: String?,
summary: String?,
imageURL: String?,
+ thumbnailURL: String?,
bannerImageURL: String?,
datePublished: Date?,
dateModified: Date?,
authors: Set?,
tags: Set?,
- attachments: Set?) {
+ attachments: [ParsedAttachment]?) {
self.syncServiceID = syncServiceID
self.uniqueID = uniqueID
self.feedURL = feedURL
@@ -58,6 +60,7 @@ public struct ParsedItem: Hashable, Sendable {
self.markdown = markdown
self.summary = summary
self.imageURL = imageURL
+ self.thumbnailURL = thumbnailURL
self.bannerImageURL = bannerImageURL
self.datePublished = datePublished
self.dateModified = dateModified
diff --git a/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift b/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift
index a032123cf..f78906edf 100644
--- a/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift
+++ b/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift
@@ -46,6 +46,8 @@ private final class AtomDelegate: XMLSAXParserDelegate {
// inside of namespaced section (, for instance).
private var namespaceElementDepth = 0
+ private var mediaElementTracker = MediaElementTracker()
+
// Attributes per open element.
private var attributesStack: [XMLAttributes] = []
@@ -77,7 +79,7 @@ private final class AtomDelegate: XMLSAXParserDelegate {
// If no logo, fall back to icon for both.
let iconURL = logoURLString ?? iconURLString
let faviconURL = iconURLString
- let parsedItems = Set(items.map { $0.toParsedItem(feedURL: feedURLString) })
+ let parsedItems = Set(items.map { $0.toParsedItem(feedURL: feedURLString, feedImageURL: iconURL) })
return ParsedFeed(
type: .atom,
@@ -121,6 +123,16 @@ private final class AtomDelegate: XMLSAXParserDelegate {
namespaceElementDepth += 1
return
}
+ if parsingArticle && namespace.isMediaRSS {
+ if let currentArticle, mediaElementTracker.start(localName: localName, attributes: attributes, item: currentArticle, parser: parser, resolveURL: resolvedURLString) {
+ namespaceElementDepth = 1
+ }
+ return
+ }
+ if mediaElementTracker.containerDepth > 0 {
+ namespaceElementDepth = 1
+ return
+ }
if parsingArticle && namespace.prefix != nil {
// Skip this namespaced element and its entire subtree, so a nested
// unprefixed element (e.g. Shopify's Default Title ) can't be
@@ -132,6 +144,7 @@ private final class AtomDelegate: XMLSAXParserDelegate {
if localName.equals("entry") {
parsingArticle = true
items.append(RSSItem())
+ mediaElementTracker.reset()
return
}
@@ -228,6 +241,13 @@ private final class AtomDelegate: XMLSAXParserDelegate {
return
}
+ if parsingArticle && namespace.isMediaRSS {
+ if let currentArticle {
+ mediaElementTracker.end(localName: localName, item: currentArticle, parser: parser)
+ }
+ return
+ }
+
if parsingAuthor {
handleAuthorElementEnd(parser: parser, localName: localName, namespace: namespace)
return
@@ -315,8 +335,8 @@ private final class AtomDelegate: XMLSAXParserDelegate {
if rel == "enclosure" {
let length = Int(attributes["length"] ?? "") ?? 0
let sizeInBytes = length > 0 ? length : nil
- if let attachment = ParsedAttachment(url: resolved, mimeType: attributes["type"], title: attributes["title"], sizeInBytes: sizeInBytes, durationInSeconds: nil) {
- article.attachments.insert(attachment)
+ if let attachment = ParsedAttachment(url: resolved, mimeType: attributes["type"], title: attributes["title"], sizeInBytes: sizeInBytes, durationInSeconds: nil, width: nil, height: nil, medium: nil) {
+ article.attachments.append(attachment)
}
return
}
diff --git a/Modules/RSParser/Sources/RSParser/Feeds/XML/MediaRSS.swift b/Modules/RSParser/Sources/RSParser/Feeds/XML/MediaRSS.swift
new file mode 100644
index 000000000..05e32bcf2
--- /dev/null
+++ b/Modules/RSParser/Sources/RSParser/Feeds/XML/MediaRSS.swift
@@ -0,0 +1,170 @@
+//
+// MediaRSS.swift
+// RSParser
+//
+// Created by Brent Simmons on 10/22/26.
+//
+
+import Foundation
+
+/// Media RSS and iTunes helpers shared by the RSS and Atom parsers.
+enum MediaRSS {
+
+ /// Attachment from a `media:content` element’s attributes. `url` is the resolved `url` attribute.
+ static func attachment(url: String, attributes: XMLAttributes) -> ParsedAttachment? {
+
+ let mimeType = attributes.value(forCaseInsensitiveName: "type")
+ // The spec says fileSize. Some feeds (atp.fm) use length, as in RSS enclosures.
+ let sizeInBytes = positiveInt(attributes.value(forCaseInsensitiveName: "fileSize") ?? attributes.value(forCaseInsensitiveName: "length"))
+ let durationInSeconds = ParsedAttachment.durationInSeconds(attributes.value(forCaseInsensitiveName: "duration"))
+ let width = positiveInt(attributes.value(forCaseInsensitiveName: "width"))
+ let height = positiveInt(attributes.value(forCaseInsensitiveName: "height"))
+ let mediumValue = attributes.value(forCaseInsensitiveName: "medium")
+ let medium = ParsedAttachment.Medium(mediaRSSValue: mediumValue)
+
+ return ParsedAttachment(url: url, mimeType: mimeType, title: nil, sizeInBytes: sizeInBytes, durationInSeconds: durationInSeconds, width: width, height: height, medium: medium)
+ }
+
+ private static let gravatarHost = "gravatar.com"
+ private static let gravatarSubdomainSuffix = ".gravatar.com"
+ private static let gravatarAvatarPathPrefix = "/avatar/"
+
+ static func isGravatar(_ url: URL) -> Bool {
+ guard let host = url.host()?.lowercased() else {
+ return false
+ }
+ let isGravatarHost = host == gravatarHost || host.hasSuffix(gravatarSubdomainSuffix)
+ return isGravatarHost && url.path().hasPrefix(gravatarAvatarPathPrefix)
+ }
+
+ static func isDefault(_ attributes: XMLAttributes) -> Bool {
+ attributes.value(forCaseInsensitiveName: "isDefault")?.lowercased() == "true"
+ }
+
+ private static func positiveInt(_ s: String?) -> Int? {
+ guard let s, let value = Int(s.trimmingCharacters(in: .whitespacesAndNewlines)), value > 0 else {
+ return nil
+ }
+ return value
+ }
+}
+
+/// Tracks `media:group` and `media:content` while parsing an item, adding attachments,
+/// the thumbnail, the description, and Gravatar titles to the item. Used by the RSS and Atom parsers.
+struct MediaElementTracker {
+
+ /// Depth inside `media:group`, `media:content`, `media:description`, and a Gravatar’s `media:title`. The parsers skip
+ /// non-Media RSS elements in there, so an unprefixed child (``)
+ /// can’t be mistaken for one of the item’s own elements.
+ private(set) var containerDepth = 0
+
+ private var group: MediaGroup?
+
+ /// Set inside a `media:content` that’s a Gravatar avatar, so its `media:title` is kept.
+ private var gravatarURL: String?
+
+ mutating func reset() {
+ containerDepth = 0
+ group = nil
+ gravatarURL = nil
+ }
+
+ /// Returns true when the parser should skip the element’s subtree.
+ mutating func start(localName: ArraySlice, attributes: XMLAttributes, item: RSSItem, parser: XMLSAXParser, resolveURL: (String) -> String?) -> Bool {
+ if localName.equals("group") {
+ group = MediaGroup()
+ containerDepth += 1
+ return false
+ }
+
+ if localName.equals("content") {
+ if let urlString = attributes.value(forCaseInsensitiveName: "url"), let url = resolveURL(urlString), let attachment = MediaRSS.attachment(url: url, attributes: attributes) {
+ if group != nil {
+ group?.add(attachment, isDefault: MediaRSS.isDefault(attributes))
+ } else {
+ item.attachments.append(attachment)
+ if let parsedURL = URL(string: url), MediaRSS.isGravatar(parsedURL) {
+ gravatarURL = url
+ }
+ }
+ }
+ containerDepth += 1
+ return false
+ }
+
+ if localName.equals("title"), gravatarURL != nil {
+ parser.beginStoringCharacters()
+ containerDepth += 1
+ return false
+ }
+
+ if localName.equals("description") {
+ if item.mediaDescription == nil {
+ item.mediaDescriptionIsHTML = attributes.value(forCaseInsensitiveName: "type")?.lowercased() == "html"
+ parser.beginStoringCharacters()
+ }
+ containerDepth += 1
+ return false
+ }
+
+ if localName.equals("thumbnail"), item.thumbnailURL == nil, let urlString = attributes.value(forCaseInsensitiveName: "url"), !urlString.isEmpty {
+ item.thumbnailURL = resolveURL(urlString)
+ }
+ return true
+ }
+
+ mutating func end(localName: ArraySlice, item: RSSItem, parser: XMLSAXParser) {
+ if localName.equals("group") {
+ if let attachment = group?.chosenAttachment {
+ item.attachments.append(attachment)
+ }
+ group = nil
+ containerDepth -= 1
+ } else if localName.equals("content") {
+ gravatarURL = nil
+ containerDepth -= 1
+ } else if localName.equals("title") {
+ if let gravatarURL, let title = parser.currentStringWithTrimmedWhitespace, !title.isEmpty {
+ item.gravatarTitlesByURL[gravatarURL] = title
+ }
+ containerDepth -= 1
+ } else if localName.equals("description") {
+ if item.mediaDescription == nil {
+ item.mediaDescription = parser.currentStringWithTrimmedWhitespace
+ }
+ containerDepth -= 1
+ }
+ }
+}
+
+/// Collects the renditions in a `media:group`. They’re alternates of one thing,
+/// so only one is kept: the `isDefault` one, else the first.
+private struct MediaGroup {
+
+ private var defaultAttachment: ParsedAttachment?
+ private var firstAttachment: ParsedAttachment?
+
+ var chosenAttachment: ParsedAttachment? {
+ defaultAttachment ?? firstAttachment
+ }
+
+ mutating func add(_ attachment: ParsedAttachment, isDefault: Bool) {
+ if firstAttachment == nil {
+ firstAttachment = attachment
+ }
+ if isDefault && defaultAttachment == nil {
+ defaultAttachment = attachment
+ }
+ }
+}
+
+extension ParsedAttachment.Medium {
+
+ /// Case-insensitive. Nil for values the Media RSS spec doesn’t define.
+ public init?(mediaRSSValue: String?) {
+ guard let mediaRSSValue else {
+ return nil
+ }
+ self.init(rawValue: mediaRSSValue.trimmingCharacters(in: .whitespacesAndNewlines).lowercased())
+ }
+}
diff --git a/Modules/RSParser/Sources/RSParser/Feeds/XML/RSSItem.swift b/Modules/RSParser/Sources/RSParser/Feeds/XML/RSSItem.swift
index c98243bfd..399f2ba57 100644
--- a/Modules/RSParser/Sources/RSParser/Feeds/XML/RSSItem.swift
+++ b/Modules/RSParser/Sources/RSParser/Feeds/XML/RSSItem.swift
@@ -22,7 +22,14 @@ final class RSSItem {
var datePublished: Date?
var dateModified: Date?
var authors: Set = []
- var attachments: Set = []
+ var attachments: [ParsedAttachment] = []
+ var thumbnailURL: String?
+ var itunesImageURL: String?
+ var itunesDurationInSeconds: Int?
+ var mediaDescription: String?
+ var mediaDescriptionIsHTML = false
+ /// `media:title` of each Gravatar `media:content`, by URL.
+ var gravatarTitlesByURL = [String: String]()
/// Returns `guid` if present. Otherwise MD5-hashes available properties
/// to build the most likely stable ID.
@@ -62,7 +69,8 @@ final class RSSItem {
return s.md5String
}
- func toParsedItem(feedURL: String) -> ParsedItem {
+ /// Attachments at `feedImageURL` are skipped. Substack lists the feed’s image as an enclosure on posts that have no image of their own.
+ func toParsedItem(feedURL: String, feedImageURL: String?) -> ParsedItem {
// If body is empty and summary has content,
// promote summary to body and drop summary.
var contentHTML = body
@@ -72,6 +80,18 @@ final class RSSItem {
itemSummary = nil
}
+ // With no body or summary, fall back to media:description (YouTube, for instance).
+ var contentText: String?
+ if contentHTML == nil || contentHTML?.isEmpty == true, let mediaDescription {
+ if mediaDescriptionIsHTML {
+ contentHTML = mediaDescription
+ } else {
+ contentText = mediaDescription
+ }
+ }
+
+ let (authorsWithAvatars, avatarURLs) = authorsWithGravatars()
+
return ParsedItem(
syncServiceID: nil,
uniqueID: uniqueID,
@@ -81,16 +101,106 @@ final class RSSItem {
title: title,
language: language,
contentHTML: contentHTML,
- contentText: nil,
+ contentText: contentText,
markdown: markdown,
summary: itemSummary,
- imageURL: nil,
+ imageURL: itunesImageURL,
+ thumbnailURL: thumbnailURL,
bannerImageURL: nil,
datePublished: datePublished,
dateModified: dateModified,
- authors: authors.isEmpty ? nil : authors,
+ authors: authorsWithAvatars.isEmpty ? nil : authorsWithAvatars,
tags: nil,
- attachments: attachments.isEmpty ? nil : attachments
+ attachments: mergedAttachments(attachments.filter { !avatarURLs.contains($0.url) && $0.url != feedImageURL })
)
}
+
+ /// WordPress adds each post author’s Gravatar as a `media:content` titled with the author’s username.
+ /// A match becomes the author’s avatar instead of an attachment.
+ private func authorsWithGravatars() -> (authors: Set, avatarURLs: Set) {
+ var avatarURLs = Set()
+ let authorsWithAvatars = Set(authors.map { author in
+ guard author.avatarURL == nil, let avatarURL = gravatarURL(author) else {
+ return author
+ }
+ avatarURLs.insert(avatarURL)
+ return ParsedAuthor(name: author.name, url: author.url, avatarURL: avatarURL, emailAddress: author.emailAddress)
+ })
+ return (authorsWithAvatars, avatarURLs)
+ }
+
+ /// The Gravatar titled with the author’s name, or, with one author and one Gravatar, that Gravatar.
+ /// The username often differs from the name, as with “halmueller” and “Hal Mueller”.
+ private func gravatarURL(_ author: ParsedAuthor) -> String? {
+ if let name = author.name, let matchingURL = gravatarTitlesByURL.first(where: { $0.value.caseInsensitiveCompare(name) == .orderedSame })?.key {
+ return matchingURL
+ }
+ guard authors.count == 1, gravatarTitlesByURL.count == 1 else {
+ return nil
+ }
+ return gravatarTitlesByURL.first?.key
+ }
+
+ /// Podcast feeds often list the same file as both `` and `media:content`,
+ /// so attachments with the same URL are merged into one, in the place of the first.
+ /// Renditions of one image at different widths are merged into the widest, in the place of the first.
+ /// `itunes:duration` applies to audio and video attachments that don’t have their own duration.
+ private func mergedAttachments(_ attachments: [ParsedAttachment]) -> [ParsedAttachment]? {
+ var mergedAttachments = [ParsedAttachment]()
+ var indexesByURL = [String: Int]()
+ var indexesByRenditionKey = [String: Int]()
+ for attachment in attachments {
+ if let index = indexesByURL[attachment.url] {
+ mergedAttachments[index] = mergedAttachments[index].filledIn(from: attachment)
+ continue
+ }
+ let renditionKey = Self.renditionKey(attachment)
+ if let renditionKey, let index = indexesByRenditionKey[renditionKey], let mergedWidth = mergedAttachments[index].width, let width = attachment.width {
+ if width > mergedWidth {
+ mergedAttachments[index] = attachment
+ }
+ indexesByURL[attachment.url] = index
+ continue
+ }
+ indexesByURL[attachment.url] = mergedAttachments.count
+ if let renditionKey {
+ indexesByRenditionKey[renditionKey] = mergedAttachments.count
+ }
+ mergedAttachments.append(attachment)
+ }
+ guard !mergedAttachments.isEmpty else {
+ return nil
+ }
+
+ guard let itunesDurationInSeconds else {
+ return mergedAttachments
+ }
+ return mergedAttachments.map { attachment in
+ guard attachment.durationInSeconds == nil, Self.isAudioOrVideo(attachment) else {
+ return attachment
+ }
+ return attachment.withDurationInSeconds(itunesDurationInSeconds)
+ }
+ }
+
+ /// The URL without its query, for an attachment with a width and a query.
+ /// The Guardian lists each image three times, as sibling `media:content` elements that differ only in `?width=`.
+ private static func renditionKey(_ attachment: ParsedAttachment) -> String? {
+ guard attachment.width != nil, var components = URLComponents(string: attachment.url), components.query != nil else {
+ return nil
+ }
+ components.query = nil
+ components.fragment = nil
+ return components.string
+ }
+
+ private static func isAudioOrVideo(_ attachment: ParsedAttachment) -> Bool {
+ if attachment.medium == .audio || attachment.medium == .video {
+ return true
+ }
+ guard let mimeType = attachment.mimeType?.lowercased() else {
+ return false
+ }
+ return mimeType.hasPrefix("audio/") || mimeType.hasPrefix("video/")
+ }
}
diff --git a/Modules/RSParser/Sources/RSParser/Feeds/XML/RSSParser.swift b/Modules/RSParser/Sources/RSParser/Feeds/XML/RSSParser.swift
index ea936c01b..daf6b79b8 100644
--- a/Modules/RSParser/Sources/RSParser/Feeds/XML/RSSParser.swift
+++ b/Modules/RSParser/Sources/RSParser/Feeds/XML/RSSParser.swift
@@ -43,6 +43,8 @@ private final class RSSDelegate: XMLSAXParserDelegate {
// inside of namespaced section (, for instance).
private var namespaceElementDepth = 0
+ private var mediaElementTracker = MediaElementTracker()
+
init(urlString: String) {
self.feedURLString = urlString
}
@@ -50,7 +52,7 @@ private final class RSSDelegate: XMLSAXParserDelegate {
// MARK: Building output
func buildParsedFeed() -> ParsedFeed {
- let parsedItems = Set(items.map { $0.toParsedItem(feedURL: feedURLString) })
+ let parsedItems = Set(items.map { $0.toParsedItem(feedURL: feedURLString, feedImageURL: channelImageURLString) })
return ParsedFeed(
type: .rss,
title: title,
@@ -88,6 +90,27 @@ private final class RSSDelegate: XMLSAXParserDelegate {
namespaceElementDepth += 1
return
}
+ if parsingArticle && namespace.isMediaRSS {
+ if let currentItem, mediaElementTracker.start(localName: localName, attributes: attributes, item: currentItem, parser: parser, resolveURL: resolveURL) {
+ namespaceElementDepth = 1
+ }
+ return
+ }
+ if parsingArticle && namespace.isITunes && localName.equals("duration") {
+ parser.beginStoringCharacters()
+ return
+ }
+ if parsingArticle && namespace.isITunes && localName.equals("image") {
+ if let currentItem, currentItem.itunesImageURL == nil, let href = attributes.value(forCaseInsensitiveName: "href"), !href.isEmpty {
+ currentItem.itunesImageURL = resolveURL(href)
+ }
+ namespaceElementDepth = 1
+ return
+ }
+ if mediaElementTracker.containerDepth > 0 {
+ namespaceElementDepth = 1
+ return
+ }
if parsingArticle && namespace.prefix != nil
&& !namespace.isDublinCore && !namespace.isContent && !namespace.isSource {
// Skip this element (in an unexpected namespace) and its subtree, so a nested
@@ -129,6 +152,7 @@ private final class RSSDelegate: XMLSAXParserDelegate {
if isUnprefixed && localName.equals("item") {
items.append(RSSItem())
parsingArticle = true
+ mediaElementTracker.reset()
if isRDF, let about = currentAttributes["rdf:about"], !about.isEmpty {
currentItem?.guid = about
@@ -165,6 +189,13 @@ private final class RSSDelegate: XMLSAXParserDelegate {
return
}
+ if parsingArticle && namespace.isMediaRSS {
+ if let currentItem {
+ mediaElementTracker.end(localName: localName, item: currentItem, parser: parser)
+ }
+ return
+ }
+
if isRDF && localName.equals("RDF") {
endRSSFound = true
return
@@ -237,6 +268,10 @@ private final class RSSDelegate: XMLSAXParserDelegate {
}
return
}
+ if namespace.isITunes && localName.equals("duration") {
+ article.itunesDurationInSeconds = ParsedAttachment.durationInSeconds(parser.currentStringWithTrimmedWhitespace)
+ return
+ }
// `source:markdown` — scripting.com's namespace, used by WordLand-generated feeds.
if namespace.isSource && localName.equals("markdown") {
article.markdown = parser.currentStringWithTrimmedWhitespace
@@ -293,8 +328,8 @@ private final class RSSDelegate: XMLSAXParserDelegate {
let length = Int(currentAttributes["length"] ?? "") ?? 0
let mimeType = currentAttributes["type"]
let sizeInBytes = length > 0 ? length : nil
- if let attachment = ParsedAttachment(url: url, mimeType: mimeType, title: nil, sizeInBytes: sizeInBytes, durationInSeconds: nil) {
- article.attachments.insert(attachment)
+ if let attachment = ParsedAttachment(url: url, mimeType: mimeType, title: nil, sizeInBytes: sizeInBytes, durationInSeconds: nil, width: nil, height: nil, medium: nil) {
+ article.attachments.append(attachment)
}
}
diff --git a/Modules/RSParser/Sources/RSParser/HTML/HTMLAttributes.swift b/Modules/RSParser/Sources/RSParser/HTML/HTMLAttributes.swift
index e2550c26a..334fb4856 100644
--- a/Modules/RSParser/Sources/RSParser/HTML/HTMLAttributes.swift
+++ b/Modules/RSParser/Sources/RSParser/HTML/HTMLAttributes.swift
@@ -33,7 +33,7 @@ public struct HTMLAttributes: Sendable {
/// Case-insensitive lookup. `name` must be all lowercase.
public subscript(name: String) -> String? {
- let needle = Array(name.utf8)
+ let needle = name.utf8
for attribute in attributes {
if attribute.name.count != needle.count {
continue
diff --git a/Modules/RSParser/Sources/RSParser/HTML/HTMLImageAttributeInserter.swift b/Modules/RSParser/Sources/RSParser/HTML/HTMLImageAttributeInserter.swift
new file mode 100644
index 000000000..f38d68c17
--- /dev/null
+++ b/Modules/RSParser/Sources/RSParser/HTML/HTMLImageAttributeInserter.swift
@@ -0,0 +1,84 @@
+//
+// HTMLImageAttributeInserter.swift
+// RSParser
+//
+// Created by Brent Simmons on 10/27/26.
+//
+
+import Foundation
+
+/// Inserts attributes at the start of the ` ` tags that load a given URL from `src`.
+///
+/// HTML uses the first of two attributes with the same name, so an inserted `src`
+/// replaces the original one, which stays in the tag unchanged.
+///
+/// Skips images whose `src` a web view may not load: those with `srcset`,
+/// those inside ``, and those with `data-canonical-src`, which script replaces `src` with.
+public enum HTMLImageAttributeInserter {
+
+ /// `attributes` is inserted as is, so it must be escaped HTML, starting with a space.
+ public static func insertingAttributes(_ attributes: String, intoImagesWithSource urlString: String, html: String, baseURL: URL?) -> String {
+ let bytes = Array(html.utf8)
+ let delegate = InserterDelegate(urlString: urlString, baseURL: baseURL)
+ let scanner = HTMLScanner(delegate: delegate)
+ scanner.parse(bytes)
+ guard !delegate.insertionOffsets.isEmpty else {
+ return html
+ }
+
+ let attributeBytes = Array(attributes.utf8)
+ var result = [UInt8]()
+ result.reserveCapacity(bytes.count + attributeBytes.count * delegate.insertionOffsets.count)
+ var copyStart = 0
+ for offset in delegate.insertionOffsets {
+ result.append(contentsOf: bytes[copyStart.., attributes: HTMLAttributes, selfClosing: Bool) {
+ if HTMLScanner.tagNameEqualsIgnoringCase(name, Self.pictureBytes[...]) {
+ if !selfClosing {
+ pictureDepth += 1
+ }
+ return
+ }
+ guard pictureDepth == 0, HTMLScanner.tagNameEqualsIgnoringCase(name, Self.imgBytes[...]) else {
+ return
+ }
+ guard attributes["srcset"] == nil, attributes["data-canonical-src"] == nil else {
+ return
+ }
+ if HTMLImageParser.resolvedURLString(attributes["src"], baseURL: baseURL) == urlString {
+ // The name slice’s indices are offsets into the scanned bytes.
+ insertionOffsets.append(name.endIndex)
+ }
+ }
+
+ func htmlScanner(_ scanner: HTMLScanner, didEndTag name: ArraySlice) {
+ if pictureDepth > 0, HTMLScanner.tagNameEqualsIgnoringCase(name, Self.pictureBytes[...]) {
+ pictureDepth -= 1
+ }
+ }
+}
diff --git a/Modules/RSParser/Sources/RSParser/HTML/HTMLImageParser.swift b/Modules/RSParser/Sources/RSParser/HTML/HTMLImageParser.swift
new file mode 100644
index 000000000..77a83e9cf
--- /dev/null
+++ b/Modules/RSParser/Sources/RSParser/HTML/HTMLImageParser.swift
@@ -0,0 +1,206 @@
+//
+// HTMLImageParser.swift
+// RSParser
+//
+// Created by Brent Simmons on 10/25/26.
+//
+
+import Foundation
+
+/// Finds the ` `s in an HTML document that pass `SignificantImageFilter`,
+/// which also sees the enclosing `` link so it can reject share buttons.
+/// Stops scanning once it has found `maximumCount`.
+///
+/// Tries `data-lazy-srcset`, `data-srcset`, `data-lazy-src`, `data-src`, `data-original`,
+/// `srcset`, and `src`, in that order, and uses the first that passes the filter.
+/// Lazy-loading images often have a placeholder in `src`.
+public enum HTMLImageParser {
+
+ private static let dataURLPrefix = "data:"
+
+ /// Absolute URLs, resolved against `baseURL`, in document order, with none repeated.
+ public static func significantImageURLStrings(html: String, baseURL: URL?, maximumCount: Int) -> [String] {
+ let delegate = ImageParserDelegate(baseURL: baseURL, maximumCount: maximumCount)
+ let scanner = HTMLScanner(delegate: delegate)
+ scanner.parse(Array(html.utf8))
+ return delegate.urlStrings
+ }
+
+ /// Nil for an empty string or a `data:` URL.
+ static func resolvedURLString(_ urlString: String?, baseURL: URL?) -> String? {
+ guard let urlString, !isDataURL(urlString) else {
+ return nil
+ }
+ let trimmedURLString = urlString.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmedURLString.isEmpty else {
+ return nil
+ }
+ return URL(string: trimmedURLString, relativeTo: baseURL)?.absoluteString
+ }
+
+ /// Looks at only the start of the string, since an inline image can be megabytes.
+ private static func isDataURL(_ urlString: String) -> Bool {
+ urlString.drop(while: \.isWhitespace).prefix(dataURLPrefix.count).lowercased() == dataURLPrefix
+ }
+}
+
+// MARK: - Delegate
+
+private final class ImageParserDelegate: HTMLScannerDelegate {
+
+ private let baseURL: URL?
+ private let maximumCount: Int
+ private(set) var urlStrings = [String]()
+ private var enclosingLinkURLString: String?
+
+ private static let imgBytes: [UInt8] = Array("img".utf8)
+ private static let anchorBytes: [UInt8] = Array("a".utf8)
+ private static let lazySrcsetAttributeNames = ["data-lazy-srcset", "data-srcset"]
+ private static let lazySourceAttributeNames = ["data-lazy-src", "data-src", "data-original"]
+ /// Wide enough for a timeline thumbnail at its largest.
+ private static let preferredSrcsetWidth: Double = 1200
+
+ init(baseURL: URL?, maximumCount: Int) {
+ self.baseURL = baseURL
+ self.maximumCount = maximumCount
+ }
+
+ func htmlScanner(_ scanner: HTMLScanner,
+ didStartTag name: ArraySlice,
+ attributes: HTMLAttributes,
+ selfClosing: Bool) {
+ if HTMLScanner.tagNameEqualsIgnoringCase(name, Self.anchorBytes[...]) {
+ enclosingLinkURLString = resolvedURLString(attributes["href"])
+ return
+ }
+ guard urlStrings.count < maximumCount, HTMLScanner.tagNameEqualsIgnoringCase(name, Self.imgBytes[...]) else {
+ return
+ }
+
+ let style = styleProperties(attributes["style"])
+ if attributes["hidden"] != nil || style["display"]?.hasPrefix("none") == true {
+ return
+ }
+
+ // CSS overrides the attributes.
+ let width = pixelDimension(style["width"]) ?? pixelDimension(attributes["width"])
+ let height = pixelDimension(style["height"]) ?? pixelDimension(attributes["height"])
+ // Before resolving any URLs, since tracking pixels are common.
+ guard SignificantImageFilter.hasSignificantDimensions(width: width, height: height) else {
+ return
+ }
+ let htmlClass = attributes["class"]
+ for urlString in imageURLStrings(attributes) {
+ if SignificantImageFilter.isSignificant(urlString: urlString, width: width, height: height, htmlClass: htmlClass, enclosingLinkURLString: enclosingLinkURLString) {
+ if !urlStrings.contains(urlString) {
+ urlStrings.append(urlString)
+ }
+ if urlStrings.count >= maximumCount {
+ scanner.stopParsing()
+ }
+ return
+ }
+ }
+ }
+
+ func htmlScanner(_ scanner: HTMLScanner,
+ didEndTag name: ArraySlice) {
+ if HTMLScanner.tagNameEqualsIgnoringCase(name, Self.anchorBytes[...]) {
+ enclosingLinkURLString = nil
+ }
+ }
+
+ // MARK: Helpers
+
+ /// Resolved as needed, since usually the first is used.
+ private func imageURLStrings(_ attributes: HTMLAttributes) -> some Sequence {
+ var sources = Self.lazySrcsetAttributeNames.compactMap { attributes[$0] }.compactMap(preferredSrcsetCandidate)
+ sources += Self.lazySourceAttributeNames.compactMap { attributes[$0] }
+ if let srcset = attributes["srcset"], let candidate = preferredSrcsetCandidate(srcset) {
+ sources.append(candidate)
+ }
+ if let src = attributes["src"] {
+ sources.append(src)
+ }
+ return sources.lazy.compactMap { self.resolvedURLString($0) }
+ }
+
+ private func resolvedURLString(_ urlString: String?) -> String? {
+ HTMLImageParser.resolvedURLString(urlString, baseURL: baseURL)
+ }
+
+ /// The narrowest URL with a width descriptor (`640w`) of at least `preferredSrcsetWidth`.
+ /// Otherwise, the URL with the largest width or density (`2x`) descriptor. A candidate with no descriptor counts as `1x`.
+ private func preferredSrcsetCandidate(_ srcset: String) -> String? {
+ var narrowestWideEnough: (url: Substring, size: Double)?
+ var largest: (url: Substring, size: Double)?
+ var remaining = srcset[...]
+
+ while true {
+ remaining = remaining.drop { $0.isWhitespace || $0 == "," }
+ if remaining.isEmpty {
+ break
+ }
+
+ var url = remaining.prefix { !$0.isWhitespace }
+ remaining = remaining.dropFirst(url.count)
+
+ // A URL ending in a comma has no descriptor.
+ var descriptor: Substring = ""
+ if url.hasSuffix(",") {
+ while url.hasSuffix(",") {
+ url = url.dropLast()
+ }
+ } else {
+ descriptor = remaining.prefix { $0 != "," }
+ remaining = remaining.dropFirst(descriptor.count)
+ }
+
+ // A descriptor can have a second part, as in `400w 300h`.
+ let sizeDescriptor = descriptor.split(whereSeparator: \.isWhitespace).first ?? ""
+ let size = Double(sizeDescriptor.dropLast()) ?? 1
+ if url.isEmpty {
+ continue
+ }
+ if sizeDescriptor.hasSuffix("w"), size >= Self.preferredSrcsetWidth, size < narrowestWideEnough?.size ?? .infinity {
+ narrowestWideEnough = (url: url, size: size)
+ }
+ if size > largest?.size ?? -.infinity {
+ largest = (url: url, size: size)
+ }
+ }
+
+ guard let candidate = narrowestWideEnough ?? largest else {
+ return nil
+ }
+ return String(candidate.url)
+ }
+
+ /// Lowercase property names and values from a `style` attribute.
+ private func styleProperties(_ style: String?) -> [String: String] {
+ guard let style else {
+ return [:]
+ }
+ var properties = [String: String]()
+ for declaration in style.split(separator: ";") {
+ let nameAndValue = declaration.split(separator: ":", maxSplits: 1)
+ guard nameAndValue.count == 2 else {
+ continue
+ }
+ let name = nameAndValue[0].trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ properties[name] = nameAndValue[1].trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ }
+ return properties
+ }
+
+ /// `"300"` and `"300px"` are pixel dimensions. Percentages and other units are not.
+ private func pixelDimension(_ value: String?) -> Int? {
+ guard var value = value?.trimmingCharacters(in: .whitespaces).lowercased() else {
+ return nil
+ }
+ if value.hasSuffix("px") {
+ value.removeLast(2)
+ }
+ return Int(value)
+ }
+}
diff --git a/Modules/RSParser/Sources/RSParser/HTML/HTMLLink.swift b/Modules/RSParser/Sources/RSParser/HTML/HTMLLink.swift
index 55b8c0c18..c687a1e3c 100644
--- a/Modules/RSParser/Sources/RSParser/HTML/HTMLLink.swift
+++ b/Modules/RSParser/Sources/RSParser/HTML/HTMLLink.swift
@@ -5,7 +5,7 @@
// Created by Brent Simmons on 4/20/26.
//
-// A single `` element harvested from an HTML document.
+// A single ` ` element parsed from an HTML document.
// Any field may be nil because HTML can be malformed.
public struct HTMLLink: Sendable {
diff --git a/Modules/RSParser/Sources/RSParser/HTML/HTMLMetadataParser.swift b/Modules/RSParser/Sources/RSParser/HTML/HTMLMetadataParser.swift
index 5de1a9d24..ae13cbcba 100644
--- a/Modules/RSParser/Sources/RSParser/HTML/HTMLMetadataParser.swift
+++ b/Modules/RSParser/Sources/RSParser/HTML/HTMLMetadataParser.swift
@@ -32,7 +32,6 @@ public enum HTMLMetadataParser {
private final class MetadataParserDelegate: HTMLScannerDelegate {
private let scanPastHead: Bool
- private var finished = false
private(set) var tags: [HTMLTag] = []
init(scanPastHead: Bool) {
@@ -43,16 +42,13 @@ private final class MetadataParserDelegate: HTMLScannerDelegate {
didStartTag name: ArraySlice,
attributes: HTMLAttributes,
selfClosing: Bool) {
- if finished {
+ // Nothing after is needed, so the rest of a large page isn’t scanned.
+ if !scanPastHead && HTMLScanner.tagNameEqualsIgnoringCase(name, Self.bodyBytes[...]) {
+ scanner.stopParsing()
return
}
- if !scanPastHead && tagNameEqualsIgnoringCase(name, Self.bodyBytes) {
- finished = true
- return
- }
-
- if tagNameEqualsIgnoringCase(name, Self.linkBytes) {
+ if HTMLScanner.tagNameEqualsIgnoringCase(name, Self.linkBytes[...]) {
if attributes.isEmpty {
return
}
@@ -69,7 +65,7 @@ private final class MetadataParserDelegate: HTMLScannerDelegate {
return
}
- if tagNameEqualsIgnoringCase(name, Self.metaBytes) {
+ if HTMLScanner.tagNameEqualsIgnoringCase(name, Self.metaBytes[...]) {
if attributes.isEmpty {
return
}
@@ -82,16 +78,4 @@ private final class MetadataParserDelegate: HTMLScannerDelegate {
static let bodyBytes: [UInt8] = Array("body".utf8)
static let linkBytes: [UInt8] = Array("link".utf8)
static let metaBytes: [UInt8] = Array("meta".utf8)
-
- private func tagNameEqualsIgnoringCase(_ name: ArraySlice, _ lowercased: [UInt8]) -> Bool {
- guard name.count == lowercased.count else {
- return false
- }
- for (a, b) in zip(name, lowercased) {
- if a.asciiLowercased != b {
- return false
- }
- }
- return true
- }
}
diff --git a/Modules/RSParser/Sources/RSParser/HTML/HTMLScanner.swift b/Modules/RSParser/Sources/RSParser/HTML/HTMLScanner.swift
index e2b5885c5..395e8c964 100644
--- a/Modules/RSParser/Sources/RSParser/HTML/HTMLScanner.swift
+++ b/Modules/RSParser/Sources/RSParser/HTML/HTMLScanner.swift
@@ -12,11 +12,12 @@
//
// Differs from the XML scanner in ways HTML requires:
// - Tag names compared case-insensitively (but emitted as they appear).
-// - Content of `` / `` ends the block.
+// - Content of ` or ends the block.
- static let scriptBytes: [UInt8] = Array("script".utf8)
- static let styleBytes: [UInt8] = Array("style".utf8)
+ // only the matching end tag ends the block.
+ static let rawTextTagNames: [[UInt8]] = ["script", "style", "textarea", "title", "xmp", "noembed"].map { Array($0.utf8) }
+ static let escapableRawTextTagNames: [[UInt8]] = ["textarea", "title"].map { Array($0.utf8) }
func drive() {
- while pos < input.count {
+ while pos < input.count && !stopped {
let b = input[pos]
if b == .asciiLessThan {
scanMarkup()
@@ -148,13 +154,8 @@ private extension HTMLScanner {
let attributeView = HTMLAttributes(attributes: attributes)
delegate?.htmlScanner(self, didStartTag: nameSlice, attributes: attributeView, selfClosing: selfClosing)
- // Raw-text mode for