diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 16611e276..f5187fe6a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,8 +39,8 @@ jobs: - name: Generate Secrets Sources run: PROJECT_DIR="$GITHUB_WORKSPACE" ./buildscripts/updateSecrets.sh - - name: Select Xcode 26.3 - run: sudo xcode-select -s /Applications/Xcode_26.3.app/Contents/Developer + - name: Select Xcode 26.6 + run: sudo xcode-select -s /Applications/Xcode_26.6.app/Contents/Developer - name: Run macOS Test Plan shell: bash @@ -84,8 +84,8 @@ jobs: - name: Generate Secrets Sources run: PROJECT_DIR="$GITHUB_WORKSPACE" ./buildscripts/updateSecrets.sh - - name: Select Xcode 26.3 - run: sudo xcode-select -s /Applications/Xcode_26.3.app/Contents/Developer + - name: Select Xcode 26.6 + run: sudo xcode-select -s /Applications/Xcode_26.6.app/Contents/Developer - name: Run iOS Test Plan shell: bash diff --git a/Appcasts/netnewswire-beta.xml b/Appcasts/netnewswire-beta.xml index 75962dda8..128306774 100644 --- a/Appcasts/netnewswire-beta.xml +++ b/Appcasts/netnewswire-beta.xml @@ -6,6 +6,239 @@ Most recent NetNewsWire changes with links to updates. en + + NetNewsWire 7.3b7 + +
  • Made image cache eviction less aggressive, which should fix a loop where images get evicted, re-cached, evicted, re-cached, etc. (See this Discourse forum post.) + + ]]> + Mon, 09 Nov 2026 21:35:00 -0800 + + 15.0 + + + + NetNewsWire 7.3b6 + +
  • Added a Grayscale icons setting to Settings > Appearance — for feed icons and author avatars (article thumbnails stay in color) +
  • Made Feed Name and Date Above Title the default in the timeline +
  • Put the date above the thumbnail when small thumbnails and Feed Name and Date Above Title are both on +
  • Made timeline rows always show the author or feed name, instead of leaving that spot empty +
  • Limited articles with no title to four lines when rows show the full title with no preview +
  • Added [[primary_media]] and [[enclosures]] tags for themes — primary_media is the article’s main image, video, or audio from the feed, when the article’s HTML doesn’t already include it +
  • Allowed themes to include a template7.3.html file, which is used in 7.3 and later instead of template.html +
  • Updated the built-in themes to use [[primary_media]] and [[enclosures]] +
  • Skipped enclosure images that are the same as the feed image (as with Letters from an American), so they don’t become redundant thumbnails or primary images +
  • Skipped primary images for microblog-style (Mastodon, etc.) posts — their images appear with the enclosures at the bottom +
  • Used media:thumbnail as a fallback when an article has no other images (as with Wired) +
  • Picked the widest image when Guardian image enclosures differ only by width +
  • Fixed duplicate images in Engadget articles +
  • Fixed embedded YouTube videos (and other iframes) not loading on sites that use Optimole lazy loading +
  • Fixed blog.rust-lang.org articles — JavaScript is turned off for them, and their noscript content is shown +
  • Used an item’s only Gravatar as its author’s avatar, even when the author name is a username + + ]]> + Mon, 09 Nov 2026 10:45:00 -0800 + + 15.0 + + + + NetNewsWire 7.3b5 + +
  • Added an Appearance settings pane — appearance (system, light, or dark), sidebar text size, sidebar icons, which smart feeds to show (Today, All Unread, Starred), and the article theme and text size (moved from General) +
  • Added a Timeline settings pane — text size, feed icons (automatic, always, or never), feed icon size, thumbnails, rows (full title with no preview, or title and preview in 1 to 6 lines), separators, fading read articles, and showing the feed name and date above the title +
  • Moved the Thumbnails setting from the View menu to Settings > Timeline +
  • Made rows fit their content (variable row heights) in timeline +
  • Made separators a regular setting (it was a hidden preference) — your existing choice carries over +
  • Gave the status bar a crisper top edge, a deeper gradient, and an etched, higher-contrast divider grip +
  • Made the main window’s split view dividers a little darker in light mode + + ]]> + Sun, 07 Nov 2026 17:00:00 -0800 + + 15.0 + + + + NetNewsWire 7.3b4 + +
  • Made small thumbnails fill the space (aspect fill) — images are cropped from the sides and bottom, never the top, so faces and other important parts are more likely to stay in view +
  • Gave large thumbnails rounded corners, to match small thumbnails and feed icons +
  • Removed the background color behind thumbnails, and added a faint placeholder color that shows until a thumbnail loads +
  • Fixed footnote popover positioning near the edge of the article view and after resizing the window on Duo +
  • Fixed bug where the last article in the timeline had a separator below it (when separators are turned on via the hidden preference) + + ]]> + Fri, 06 Nov 2026 08:40:00 -0800 + + 15.0 + + + + NetNewsWire 7.3b3 + +
  • Added support for enclosures and Media RSS +
  • Added enclosures to the article view (at the bottom) — you can see images from Mastodon feeds, play an MP3, etc. +
  • Made YouTube enclosures play in the privacy-enhanced YouTube player (youtube-nocookie.com) +
  • Made the article view show plain text or media:description when an article has no HTML content +
  • Made image downloading kinder to servers — honors Retry-After, waits after errors, and limits downloads to two at a time per host +
  • Reorganized the View menu into sections — sidebar, timeline, status bar, and toolbar +
  • Added article thumbnails to the timeline — choose View > Thumbnails to pick large or small. Default is none. (Works in standard layout but not column layout) + + ]]> + Tue, 03 Nov 2026 17:00:00 -0800 + + 15.0 + + + + NetNewsWire 7.3b2 + +
  • Fixed a crash at midnight when the status bar is showing +
  • Added the last-refresh time to the status bar, and made it the default +
  • Changed the status bar to use a shorter date format +
  • Added Refresh and Show/Hide Sidebar commands to the status bar gear menu +
  • Made clicking the progress indicator in the status bar open the Current Activity window (as in NetNewsWire of Yore) +
  • Fixed bug where the status bar divider might drift from the split view divider +
  • Fixed inline footnotes in FreshRSS articles +
  • Added netnewswire, feed, feeds, and x-netnewswire-feed as allowed link schemes in the article view — so clicking a link to install a theme (for instance) works + + ]]> + Thu, 22 Oct 2026 11:20:00 -0700 + + 15.0 + + + + NetNewsWire 7.3b1 + +
  • Restored the status bar from NetNewsWire of Yore (NetNewsWire 1-3). Show and hide it via the View menu + + ]]> + Tue, 20 Oct 2026 11:35:00 -0700 + + 15.0 + + + + NetNewsWire 7.2.1 + +
  • Fixed bug where navigated-to row, in column layout, might appear under column headers +
  • Fixed bug where scroller hiding/showing could mess up sidebar layout +
  • Added magnet as an allowed link scheme + + ]]> + Tue, 20 Oct 2026 10:00:00 -0700 + + 15.0 + + + + NetNewsWire 7.2.1b1 + +
  • Fixed bug where navigated-to row, in column layout, might appear under column headers +
  • Fixed bug where scroller hiding/showing could mess up sidebar layout +
  • Added magnet as an allowed link scheme + + ]]> + Sun, 18 Oct 2026 11:40:00 -0700 + + 15.0 + + + + NetNewsWire 7.2 + View > Use Column Layout menu item. Also note the new setting for unread counts at the top of the General (first) settings tab. +

    +Changes since 7.2b4: +

      +
    • Fixed column view bug where next-unread could scroll to a row that’s hidden under the column headers +
    +Changes since 7.1.5: +
      +
    • Added unread count display setting — show the count, show a dot, or hide it — which applies to the Dock icon badge, window title, and sidebar +
    • Added column layout for the timeline — choose View > Use Column Layout +
    • Expanded View > Sort Articles By with more options (works with standard and column layouts) +
    • Made timeline sorting per window instead of one setting for the whole app +
    • Made the Add Feed sheet start with the folder or account selected in the sidebar +
    • Changed the message for adding a feed that’s already added to include the name of the folder (or folders) +
    • Fixed bug where YouTube embeds in articles showed an error instead of playing +
    • Fixed bug where embedded videos with no set height — such as Inoreader’s YouTube player — collapsed to a short strip +
    • Fixed extra whitespace at the end of Slashdot articles and paragraphs running together +
    • Fixed parsing of RSS feed titles when a feed contains a textinput section (Slashdot, for instance) +
    • Added support for the instapaper_ignore class — elements marked with it are now removed from articles +
    • Changed tabs in pre and code elements in articles to display as four spaces +
    • Improved finding feeds in a page by skipping links to PDFs, movies, and other files that can’t be feeds +
    • Changed finding a feed to use the redirected-to URL +
    • Sped up Today and unread count queries +
    • Added up to 500 characters of the HTTP error response body to Error Log entries +
    • Fixed bug where the sidebar could reopen with no width when it had been collapsed in 7.1.x +
    • Fixed a memory leak when closing a main window +
    • Fixed a possible crash when the sidebar or timeline had no visible rows +
    • Changed sorting by title and by feed to sort numbers by value — “Episode 2” comes before “Episode 10” +
    • Added support for Substack-style footnotes +
    • Improved CJK text rendering in the article view by adding text-autospace +
    • Fixed horizontal overflow of WordPress Math blocks and SVGs in the Tiqoe Dark theme +
    • Improved font sizing and fixed superscript orphans in table cells in the Tiqoe Dark theme` +
    + ]]>
    + Wed, 14 Oct 2026 08:20:00 -0700 + + 15.0 +
    + + + NetNewsWire 7.2b4 + View > Use Column Layout menu item. Also note the new setting for unread counts at the top of the General (first) settings tab. +

    +Changes since 7.2b3: +

      +
    • Fixed bug where embedded videos with no set height — such as Inoreader’s YouTube player — collapsed to a short strip +
    + ]]>
    + Sun, 11 Oct 2026 11:10:00 -0700 + + 15.0 +
    + + + NetNewsWire 7.2b3 + View > Use Column Layout menu item. Also note the new setting for unread counts at the top of the General (first) settings tab. +

    +Changes since 7.2b2: +

      +
    • Fixed the Settings layout on macOS 15 +
    • Added Spanish translations for Settings and the Sort Articles By menu +
    • Made each Settings pane size itself to fit, for languages that need more room +
    • Fixed bug where the sidebar could reopen with no width when it had been collapsed in 7.1.x +
    • Fixed a memory leak when closing a main window +
    • Fixed a possible crash when the sidebar or timeline had no visible rows +
    • Changed sorting by title and by feed to sort numbers by value — “Episode 2” comes before “Episode 10” +
    • Improved finding feeds in a page by skipping links to X, Twitter, Facebook, and Instagram, and links to files with uppercase extensions or URL queries (such as .PDF or .jpg?w=600) +
    • Fixed bug where some sites with “youtube” in their names were treated as YouTube +
    • Fixed Slashdot feed detection (for Slashdot special cases) when the feed comes through a proxy such as FeedBurner +
    • Changed VoiceOver to say “unread” for sidebar unread counts shown as dots +
    + ]]>
    + Sat, 10 Oct 2026 09:05:00 -0700 + + 15.0 +
    + NetNewsWire 7.2b2 Most recent NetNewsWire releases (not test builds). en + + NetNewsWire 7.2.1 + +
  • Fixed bug where navigated-to row, in column layout, might appear under column headers +
  • Fixed bug where scroller hiding/showing could mess up sidebar layout +
  • Added magnet as an allowed link scheme + + ]]> + Tue, 20 Oct 2026 10:00:00 -0700 + + 15.0 + + + + NetNewsWire 7.2 + +
  • Added unread count display setting — show the count, show a dot, or hide it — which applies to the Dock icon badge, window title, and sidebar +
  • Added column layout for the timeline — choose View > Use Column Layout +
  • Expanded View > Sort Articles By with more options (works with standard and column layouts) +
  • Made timeline sorting per window instead of one setting for the whole app +
  • Made the Add Feed sheet start with the folder or account selected in the sidebar +
  • Changed the message for adding a feed that’s already added to include the name of the folder (or folders) +
  • Fixed bug where YouTube embeds in articles showed an error instead of playing +
  • Fixed bug where embedded videos with no set height — such as Inoreader’s YouTube player — collapsed to a short strip +
  • Fixed extra whitespace at the end of Slashdot articles and paragraphs running together +
  • Fixed parsing of RSS feed titles when a feed contains a textinput section (Slashdot, for instance) +
  • Added support for the instapaper_ignore class — elements marked with it are now removed from articles +
  • Changed tabs in pre and code elements in articles to display as four spaces +
  • Improved finding feeds in a page by skipping links to PDFs, movies, and other files that can’t be feeds +
  • Changed finding a feed to use the redirected-to URL +
  • Sped up Today and unread count queries +
  • Added up to 500 characters of the HTTP error response body to Error Log entries +
  • Fixed bug where the sidebar could reopen with no width when it had been collapsed in 7.1.x +
  • Fixed a memory leak when closing a main window +
  • Fixed a possible crash when the sidebar or timeline had no visible rows +
  • Changed sorting by title and by feed to sort numbers by value — “Episode 2” comes before “Episode 10” +
  • Added support for Substack-style footnotes +
  • Improved CJK text rendering in the article view by adding text-autospace +
  • Fixed horizontal overflow of WordPress Math blocks and SVGs in the Tiqoe Dark theme +
  • Improved font sizing and fixed superscript orphans in table cells in the Tiqoe Dark theme + + ]]> + Wed, 14 Oct 2026 08:20:00 -0700 + + 15.0 + + NetNewsWire 7.1.5 Most recent NetNewsWire changes with links to updates. en + + NetNewsWire 7.3b7 + +
  • Made image cache eviction less aggressive, which should fix a loop where images get evicted, re-cached, evicted, re-cached, etc. (See this Discourse forum post.) + + ]]> + Mon, 09 Nov 2026 21:35:00 -0800 + + 15.0 + + + + NetNewsWire 7.3b6 + +
  • Added a Grayscale icons setting to Settings > Appearance — for feed icons and author avatars (article thumbnails stay in color) +
  • Made Feed Name and Date Above Title the default in the timeline +
  • Put the date above the thumbnail when small thumbnails and Feed Name and Date Above Title are both on +
  • Made timeline rows always show the author or feed name, instead of leaving that spot empty +
  • Limited articles with no title to four lines when rows show the full title with no preview +
  • Added [[primary_media]] and [[enclosures]] tags for themes — primary_media is the article’s main image, video, or audio from the feed, when the article’s HTML doesn’t already include it +
  • Allowed themes to include a template7.3.html file, which is used in 7.3 and later instead of template.html +
  • Updated the built-in themes to use [[primary_media]] and [[enclosures]] +
  • Skipped enclosure images that are the same as the feed image (as with Letters from an American), so they don’t become redundant thumbnails or primary images +
  • Skipped primary images for microblog-style (Mastodon, etc.) posts — their images appear with the enclosures at the bottom +
  • Used media:thumbnail as a fallback when an article has no other images (as with Wired) +
  • Picked the widest image when Guardian image enclosures differ only by width +
  • Fixed duplicate images in Engadget articles +
  • Fixed embedded YouTube videos (and other iframes) not loading on sites that use Optimole lazy loading +
  • Fixed blog.rust-lang.org articles — JavaScript is turned off for them, and their noscript content is shown +
  • Used an item’s only Gravatar as its author’s avatar, even when the author name is a username + + ]]> + Mon, 09 Nov 2026 10:45:00 -0800 + + 15.0 + + + + NetNewsWire 7.3b5 + +
  • Added an Appearance settings pane — appearance (system, light, or dark), sidebar text size, sidebar icons, which smart feeds to show (Today, All Unread, Starred), and the article theme and text size (moved from General) +
  • Added a Timeline settings pane — text size, feed icons (automatic, always, or never), feed icon size, thumbnails, rows (full title with no preview, or title and preview in 1 to 6 lines), separators, fading read articles, and showing the feed name and date above the title +
  • Moved the Thumbnails setting from the View menu to Settings > Timeline +
  • Made rows fit their content (variable row heights) in timeline +
  • Made separators a regular setting (it was a hidden preference) — your existing choice carries over +
  • Gave the status bar a crisper top edge, a deeper gradient, and an etched, higher-contrast divider grip +
  • Made the main window’s split view dividers a little darker in light mode + + ]]> + Sun, 07 Nov 2026 17:00:00 -0800 + + 15.0 + + + + NetNewsWire 7.3b4 + +
  • Made small thumbnails fill the space (aspect fill) — images are cropped from the sides and bottom, never the top, so faces and other important parts are more likely to stay in view +
  • Gave large thumbnails rounded corners, to match small thumbnails and feed icons +
  • Removed the background color behind thumbnails, and added a faint placeholder color that shows until a thumbnail loads +
  • Fixed footnote popover positioning near the edge of the article view and after resizing the window on Duo +
  • Fixed bug where the last article in the timeline had a separator below it (when separators are turned on via the hidden preference) + + ]]> + Fri, 06 Nov 2026 08:40:00 -0800 + + 15.0 + + + + NetNewsWire 7.3b3 + +
  • Added support for enclosures and Media RSS +
  • Added enclosures to the article view (at the bottom) — you can see images from Mastodon feeds, play an MP3, etc. +
  • Made YouTube enclosures play in the privacy-enhanced YouTube player (youtube-nocookie.com) +
  • Made the article view show plain text or media:description when an article has no HTML content +
  • Made image downloading kinder to servers — honors Retry-After, waits after errors, and limits downloads to two at a time per host +
  • Reorganized the View menu into sections — sidebar, timeline, status bar, and toolbar +
  • Added article thumbnails to the timeline — choose View > Thumbnails to pick large or small. Default is none. (Works in standard layout but not column layout) + + ]]> + Tue, 03 Nov 2026 17:00:00 -0800 + + 15.0 + + + + NetNewsWire 7.3b2 + +
  • Fixed a crash at midnight when the status bar is showing +
  • Added the last-refresh time to the status bar, and made it the default +
  • Changed the status bar to use a shorter date format +
  • Added Refresh and Show/Hide Sidebar commands to the status bar gear menu +
  • Made clicking the progress indicator in the status bar open the Current Activity window (as in NetNewsWire of Yore) +
  • Fixed bug where the status bar divider might drift from the split view divider +
  • Fixed inline footnotes in FreshRSS articles +
  • Added netnewswire, feed, feeds, and x-netnewswire-feed as allowed link schemes in the article view — so clicking a link to install a theme (for instance) works + + ]]> + Thu, 22 Oct 2026 11:20:00 -0700 + + 15.0 + + + + NetNewsWire 7.3b1 + +
  • Restored the status bar from NetNewsWire of Yore (NetNewsWire 1-3). Show and hide it via the View menu + + ]]> + Tue, 20 Oct 2026 11:35:00 -0700 + + 15.0 + + + + NetNewsWire 7.2.1 + +
  • Fixed bug where navigated-to row, in column layout, might appear under column headers +
  • Fixed bug where scroller hiding/showing could mess up sidebar layout +
  • Added magnet as an allowed link scheme + + ]]> + Tue, 20 Oct 2026 10:00:00 -0700 + + 15.0 + + + + NetNewsWire 7.2.1b1 + +
  • Fixed bug where navigated-to row, in column layout, might appear under column headers +
  • Fixed bug where scroller hiding/showing could mess up sidebar layout +
  • Added magnet as an allowed link scheme + + ]]> + Sun, 18 Oct 2026 11:40:00 -0700 + + 15.0 + + NetNewsWire 7.2b2 StatusBarCountMode { + switch self { + case .lastRefresh: + includingUnreadCount ? .unreadCount : .foldersAndFeeds + case .unreadCount: + .foldersAndFeeds + case .foldersAndFeeds: + .lastRefresh + } + } +} + +extension AppDefaults.Key { + static let legacyWindowState = "windowState" + static let secureWindowState = "secureWindowState" + static let useColumnLayout = "useColumnLayout" + static let timelineShowSeparators = "timelineShowSeparators" + static let legacyTimelineShowSeparators = "CorreiaSeparators" // Formerly a hidden pref + static let showStatusBar = "showStatusBar" + static let showStatusBarThemeMenu = "showStatusBarThemeMenu" + static let statusBarCountMode = "statusBarCountMode" + static let openInBrowserInBackground = "openInBrowserInBackground" + static let subscribeToFeedsInDefaultBrowser = "subscribeToFeedsInDefaultBrowser" + static let articleTextSize = "articleTextSize" + static let refreshInterval = "refreshInterval" + static let importOPMLAccountID = "importOPMLAccountID" + static let exportOPMLAccountID = "exportOPMLAccountID" + static let defaultBrowserID = "defaultBrowserID" + + // Hidden prefs + static let showDebugMenu = "ShowDebugMenu" + static let showTitleOnMainWindow = "KafasisTitleMode" + static let feedDoubleClickMarkAsRead = "GruberFeedDoubleClickMarkAsRead" + static let suppressSyncOnLaunch = "DevroeSuppressSyncOnLaunch" + static let webInspectorEnabled = "WebInspectorEnabled" + static let webInspectorStartsAttached = "__WebInspectorPageGroupLevel1__.WebKit2InspectorStartsAttached" +} + +extension AppDefaults { + + /// Stores window state prior to switching to secure state restoration. + /// + /// This is referenced temporarily, only to be able to provide migration from legacy to secure window state. + /// TODO: delete for NetNewsWire 7. + static var legacyWindowState: [AnyHashable: Any]? { + UserDefaults.standard.object(forKey: Key.legacyWindowState) as? [AnyHashable: Any] + } + + static func deleteLegacyWindowState() { + UserDefaults.standard.removeObject(forKey: Key.legacyWindowState) + } + + static var secureWindowState: Data? { + get { + UserDefaults.standard.object(forKey: Key.secureWindowState) as? Data + } + set { + UserDefaults.standard.set(newValue, forKey: Key.secureWindowState) + } + } + + static var openInBrowserInBackground: Bool { + get { + UserDefaults.standard.bool(forKey: Key.openInBrowserInBackground) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.openInBrowserInBackground) + } + } + + // Special case for this default: store/retrieve it from the shared app group + // defaults, so that it can be resolved by the Safari App Extension. + static var subscribeToFeedDefaults: UserDefaults { + if let appGroupID = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String, + let appGroupDefaults = UserDefaults(suiteName: appGroupID) { + appGroupDefaults + } else { + UserDefaults.standard + } + } + + static var subscribeToFeedsInDefaultBrowser: Bool { + get { + subscribeToFeedDefaults.bool(forKey: Key.subscribeToFeedsInDefaultBrowser) + } + set { + subscribeToFeedDefaults.set(newValue, forKey: Key.subscribeToFeedsInDefaultBrowser) + } + } + + static var importOPMLAccountID: String? { + get { + UserDefaults.standard.string(forKey: Key.importOPMLAccountID) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.importOPMLAccountID) + } + } + + static var exportOPMLAccountID: String? { + get { + UserDefaults.standard.string(forKey: Key.exportOPMLAccountID) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.exportOPMLAccountID) + } + } + + static var defaultBrowserID: String? { + get { + UserDefaults.standard.string(forKey: Key.defaultBrowserID) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.defaultBrowserID) + } + } + + static var showTitleOnMainWindow: Bool { + UserDefaults.standard.bool(forKey: Key.showTitleOnMainWindow) + } + + static var showDebugMenu: Bool { + UserDefaults.standard.bool(forKey: Key.showDebugMenu) + } + + static var feedDoubleClickMarkAsRead: Bool { + get { + UserDefaults.standard.bool(forKey: Key.feedDoubleClickMarkAsRead) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.feedDoubleClickMarkAsRead) + } + } + + static var suppressSyncOnLaunch: Bool { + get { + UserDefaults.standard.bool(forKey: Key.suppressSyncOnLaunch) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.suppressSyncOnLaunch) + } + } + + static var webInspectorEnabled: Bool { + get { + UserDefaults.standard.bool(forKey: Key.webInspectorEnabled) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.webInspectorEnabled) + } + } + + static var webInspectorStartsAttached: Bool { + get { + UserDefaults.standard.bool(forKey: Key.webInspectorStartsAttached) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.webInspectorStartsAttached) + } + } + + // Sorting is per window and lives in TimelineWindowState. These two are read-only seeds + // for a window that has no saved sort, so a setting from before per-window sorting carries over. + static var timelineSortDirection: ComparisonResult { + AppDefaults.sortDirection(for: Key.timelineSortDirection) + } + + static var timelineGroupByFeed: Bool { + UserDefaults.standard.bool(forKey: Key.timelineGroupByFeed) + } + + /// Column layout: multi-column timeline table with the article view below it, like Mail’s View > Use Column Layout. Applies to all windows. + static var useColumnLayout: Bool { + get { + UserDefaults.standard.bool(forKey: Key.useColumnLayout) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.useColumnLayout) + } + } + + /// The main window status bar. Applies to all windows. + static var showStatusBar: Bool { + get { + UserDefaults.standard.bool(forKey: Key.showStatusBar) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.showStatusBar) + } + } + + /// The status bar is off by default on macOS 26 and on by default everywhere else. + private static var showStatusBarDefault: Bool { + if #available(macOS 27.0, *) { + return true + } + if #available(macOS 26.0, *) { + return false + } + return true + } + + static var showStatusBarThemeMenu: Bool { + get { + UserDefaults.standard.bool(forKey: Key.showStatusBarThemeMenu) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.showStatusBarThemeMenu) + } + } + + static var statusBarCountMode: StatusBarCountMode { + get { + StatusBarCountMode(rawValue: UserDefaults.standard.integer(forKey: Key.statusBarCountMode)) ?? .lastRefresh + } + set { + UserDefaults.standard.set(newValue.rawValue, forKey: Key.statusBarCountMode) + } + } + + static var timelineShowSeparators: Bool { + get { + UserDefaults.standard.bool(forKey: Key.timelineShowSeparators) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.timelineShowSeparators) + NotificationCenter.default.post(name: .timelineShowSeparatorsDidChange, object: nil) + } + } + + static var articleTextSize: ArticleTextSize { + get { + let rawValue = UserDefaults.standard.integer(forKey: Key.articleTextSize) + return ArticleTextSize(rawValue: rawValue) ?? ArticleTextSize.large + } + set { + UserDefaults.standard.set(newValue.rawValue, forKey: Key.articleTextSize) + } + } + + static var refreshInterval: RefreshInterval { + get { + let rawValue = UserDefaults.standard.integer(forKey: Key.refreshInterval) + if rawValue == 2 { // Old every-10-minutes setting — now using 30 minutes as minimum. + return .every30Minutes + } + return RefreshInterval(rawValue: rawValue) ?? .every2Hours + } + set { + UserDefaults.standard.set(newValue.rawValue, forKey: Key.refreshInterval) + } + } + + @MainActor static func registerDefaults() { + // Migrate every-10-minute refresh interval to 30 minutes. + let rawValue = UserDefaults.standard.integer(forKey: Key.refreshInterval) + if rawValue == 2 { + UserDefaults.standard.set(RefreshInterval.every30Minutes.rawValue, forKey: Key.refreshInterval) + } + + migrateLegacyTimelineShowSeparators() + + #if DEBUG + let showDebugMenu = true + #else + let showDebugMenu = false + #endif + + let platformDefaults: [String: Any] = [ + Key.useColumnLayout: false, + Key.showStatusBar: Self.showStatusBarDefault, + Key.showStatusBarThemeMenu: true, + Key.statusBarCountMode: StatusBarCountMode.lastRefresh.rawValue, + "NSScrollViewShouldScrollUnderTitlebar": false, + Key.refreshInterval: RefreshInterval.every2Hours.rawValue, + Key.showDebugMenu: showDebugMenu, + Key.timelineShowSeparators: false, + Key.timelineIconDimension: IconSize.large.rawValue, + Key.timelineNumberOfLines: 3 + ] + + let defaults = commonRegisteredDefaults.merging(platformDefaults) { _, platformValue in platformValue } + UserDefaults.standard.register(defaults: defaults) + } + + /// Carries a true value over from the old hidden-pref key, then removes the old key. + private static func migrateLegacyTimelineShowSeparators() { + if UserDefaults.standard.bool(forKey: Key.legacyTimelineShowSeparators) { + UserDefaults.standard.set(true, forKey: Key.timelineShowSeparators) + } + UserDefaults.standard.removeObject(forKey: Key.legacyTimelineShowSeparators) + } +} diff --git a/Mac/AppDefaults.swift b/Mac/AppDefaults.swift deleted file mode 100644 index 7e0c5f08b..000000000 --- a/Mac/AppDefaults.swift +++ /dev/null @@ -1,439 +0,0 @@ -// -// AppDefaults.swift -// NetNewsWire -// -// Created by Brent Simmons on 9/22/17. -// Copyright © 2017 Ranchero Software. All rights reserved. -// - -import AppKit - -enum FontSize: Int { - case small = 0 - case medium = 1 - case large = 2 - case veryLarge = 3 -} - -final class AppDefaults: Sendable { - - static let defaultThemeName = "Default" - - static let shared = AppDefaults() - - struct Key { - static let firstRunDate = "firstRunDate" - static let legacyWindowState = "windowState" - static let secureWindowState = "secureWindowState" - static let lastImageCacheFlushDate = "lastImageCacheFlushDate" - static let sidebarFontSize = "sidebarFontSize" - static let timelineFontSize = "timelineFontSize" - static let timelineSortDirection = "timelineSortDirection" - static let timelineGroupByFeed = "timelineGroupByFeed" - static let useColumnLayout = "useColumnLayout" - static let detailFontSize = "detailFontSize" - static let openInBrowserInBackground = "openInBrowserInBackground" - static let subscribeToFeedsInDefaultBrowser = "subscribeToFeedsInDefaultBrowser" - static let articleTextSize = "articleTextSize" - static let refreshInterval = "refreshInterval" - static let addFeedAccountID = "addFeedAccountID" - static let addFeedFolderName = "addFeedFolderName" - static let addFolderAccountID = "addFolderAccountID" - static let importOPMLAccountID = "importOPMLAccountID" - static let exportOPMLAccountID = "exportOPMLAccountID" - static let defaultBrowserID = "defaultBrowserID" - static let currentThemeName = "currentThemeName" - static let articleContentJavascriptEnabled = "articleContentJavascriptEnabled" - - // Hidden prefs - static let showDebugMenu = "ShowDebugMenu" - static let timelineShowsSeparators = "CorreiaSeparators" - static let showTitleOnMainWindow = "KafasisTitleMode" - static let feedDoubleClickMarkAsRead = "GruberFeedDoubleClickMarkAsRead" - static let suppressSyncOnLaunch = "DevroeSuppressSyncOnLaunch" - static let webInspectorEnabled = "WebInspectorEnabled" - static let webInspectorStartsAttached = "__WebInspectorPageGroupLevel1__.WebKit2InspectorStartsAttached" - } - - private static let smallestFontSizeRawValue = FontSize.small.rawValue - private static let largestFontSizeRawValue = FontSize.veryLarge.rawValue - - let isDeveloperBuild: Bool = { - if let dev = Bundle.main.object(forInfoDictionaryKey: "DeveloperEntitlements") as? String, dev == "-dev" { - return true - } - return false - }() - - let isFirstRun: Bool = { - if UserDefaults.standard.object(forKey: Key.firstRunDate) is Date { - return false - } - firstRunDate = Date() - return true - }() - - /// Stores window state prior to switching to secure state restoration. - /// - /// This is referenced temporarily, only to be able to provide migration from legacy to secure window state. - /// TODO: delete for NetNewsWire 7. - var legacyWindowState: [AnyHashable: Any]? { - UserDefaults.standard.object(forKey: Key.legacyWindowState) as? [AnyHashable: Any] - } - - func deleteLegacyWindowState() { - UserDefaults.standard.removeObject(forKey: Key.legacyWindowState) - } - - var secureWindowState: Data? { - get { - UserDefaults.standard.object(forKey: Key.secureWindowState) as? Data - } - set { - UserDefaults.standard.set(newValue, forKey: Key.secureWindowState) - } - } - - var lastImageCacheFlushDate: Date? { - get { - return AppDefaults.date(for: Key.lastImageCacheFlushDate) - } - set { - AppDefaults.setDate(for: Key.lastImageCacheFlushDate, newValue) - } - } - - var openInBrowserInBackground: Bool { - get { - return AppDefaults.bool(for: Key.openInBrowserInBackground) - } - set { - AppDefaults.setBool(for: Key.openInBrowserInBackground, newValue) - } - } - - // Special case for this default: store/retrieve it from the shared app group - // defaults, so that it can be resolved by the Safari App Extension. - var subscribeToFeedDefaults: UserDefaults { - if let appGroupID = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String, - let appGroupDefaults = UserDefaults(suiteName: appGroupID) { - return appGroupDefaults - } else { - return UserDefaults.standard - } - } - - var subscribeToFeedsInDefaultBrowser: Bool { - get { - return subscribeToFeedDefaults.bool(forKey: Key.subscribeToFeedsInDefaultBrowser) - } - set { - subscribeToFeedDefaults.set(newValue, forKey: Key.subscribeToFeedsInDefaultBrowser) - } - } - - var sidebarFontSize: FontSize { - get { - return fontSize(for: Key.sidebarFontSize) - } - set { - AppDefaults.setFontSize(for: Key.sidebarFontSize, newValue) - } - } - - var timelineFontSize: FontSize { - get { - return fontSize(for: Key.timelineFontSize) - } - set { - AppDefaults.setFontSize(for: Key.timelineFontSize, newValue) - } - } - - var detailFontSize: FontSize { - get { - return fontSize(for: Key.detailFontSize) - } - set { - AppDefaults.setFontSize(for: Key.detailFontSize, newValue) - } - } - - var addFeedAccountID: String? { - get { - return AppDefaults.string(for: Key.addFeedAccountID) - } - set { - AppDefaults.setString(for: Key.addFeedAccountID, newValue) - } - } - - var addFeedFolderName: String? { - get { - return AppDefaults.string(for: Key.addFeedFolderName) - } - set { - AppDefaults.setString(for: Key.addFeedFolderName, newValue) - } - } - - var addFolderAccountID: String? { - get { - return AppDefaults.string(for: Key.addFolderAccountID) - } - set { - AppDefaults.setString(for: Key.addFolderAccountID, newValue) - } - } - - var importOPMLAccountID: String? { - get { - return AppDefaults.string(for: Key.importOPMLAccountID) - } - set { - AppDefaults.setString(for: Key.importOPMLAccountID, newValue) - } - } - - var exportOPMLAccountID: String? { - get { - return AppDefaults.string(for: Key.exportOPMLAccountID) - } - set { - AppDefaults.setString(for: Key.exportOPMLAccountID, newValue) - } - } - - var defaultBrowserID: String? { - get { - return AppDefaults.string(for: Key.defaultBrowserID) - } - set { - AppDefaults.setString(for: Key.defaultBrowserID, newValue) - } - } - - var currentThemeName: String? { - get { - return AppDefaults.string(for: Key.currentThemeName) - } - set { - AppDefaults.setString(for: Key.currentThemeName, newValue) - } - } - - var showTitleOnMainWindow: Bool { - return AppDefaults.bool(for: Key.showTitleOnMainWindow) - } - - var showDebugMenu: Bool { - return AppDefaults.bool(for: Key.showDebugMenu) - } - - var feedDoubleClickMarkAsRead: Bool { - get { - return AppDefaults.bool(for: Key.feedDoubleClickMarkAsRead) - } - set { - AppDefaults.setBool(for: Key.feedDoubleClickMarkAsRead, newValue) - } - } - - var suppressSyncOnLaunch: Bool { - get { - return AppDefaults.bool(for: Key.suppressSyncOnLaunch) - } - set { - AppDefaults.setBool(for: Key.suppressSyncOnLaunch, newValue) - } - } - - var webInspectorEnabled: Bool { - get { - return AppDefaults.bool(for: Key.webInspectorEnabled) - } - set { - AppDefaults.setBool(for: Key.webInspectorEnabled, newValue) - } - } - - var webInspectorStartsAttached: Bool { - get { - return AppDefaults.bool(for: Key.webInspectorStartsAttached) - } - set { - AppDefaults.setBool(for: Key.webInspectorStartsAttached, newValue) - } - } - - // Sorting is per window and lives in TimelineWindowState. These two are read-only seeds - // for a window that has no saved sort, so a setting from before per-window sorting carries over. - var timelineSortDirection: ComparisonResult { - AppDefaults.sortDirection(for: Key.timelineSortDirection) - } - - var timelineGroupByFeed: Bool { - AppDefaults.bool(for: Key.timelineGroupByFeed) - } - - /// Column layout: multi-column timeline table with the article view below it, like Mail’s View > Use Column Layout. Applies to all windows. - var useColumnLayout: Bool { - get { - AppDefaults.bool(for: Key.useColumnLayout) - } - set { - AppDefaults.setBool(for: Key.useColumnLayout, newValue) - } - } - - var timelineShowsSeparators: Bool { - return AppDefaults.bool(for: Key.timelineShowsSeparators) - } - - var articleTextSize: ArticleTextSize { - get { - let rawValue = UserDefaults.standard.integer(forKey: Key.articleTextSize) - return ArticleTextSize(rawValue: rawValue) ?? ArticleTextSize.large - } - set { - UserDefaults.standard.set(newValue.rawValue, forKey: Key.articleTextSize) - } - } - - var refreshInterval: RefreshInterval { - get { - let rawValue = UserDefaults.standard.integer(forKey: Key.refreshInterval) - if rawValue == 2 { // Old every-10-minutes setting — now using 30 minutes as minimum. - return .every30Minutes - } - return RefreshInterval(rawValue: rawValue) ?? .every2Hours - } - set { - UserDefaults.standard.set(newValue.rawValue, forKey: Key.refreshInterval) - } - } - - var isArticleContentJavascriptEnabled: Bool { - get { - UserDefaults.standard.bool(forKey: Key.articleContentJavascriptEnabled) - } - set { - UserDefaults.standard.set(newValue, forKey: Key.articleContentJavascriptEnabled) - } - } - - init() { - // Migrate every-10-minute refresh interval to 30 minutes. - let rawValue = UserDefaults.standard.integer(forKey: Key.refreshInterval) - if rawValue == 2 { - UserDefaults.standard.set(RefreshInterval.every30Minutes.rawValue, forKey: Key.refreshInterval) - } - } - - @MainActor func registerDefaults() { - #if DEBUG - let showDebugMenu = true - #else - let showDebugMenu = false - #endif - - let defaults: [String: Any] = [ - Key.sidebarFontSize: FontSize.medium.rawValue, - Key.timelineFontSize: FontSize.medium.rawValue, - Key.detailFontSize: FontSize.medium.rawValue, - Key.timelineSortDirection: ComparisonResult.orderedDescending.rawValue, - Key.timelineGroupByFeed: false, - Key.useColumnLayout: false, - "NSScrollViewShouldScrollUnderTitlebar": false, - Key.refreshInterval: RefreshInterval.every2Hours.rawValue, - Key.showDebugMenu: showDebugMenu, - Key.currentThemeName: Self.defaultThemeName, - Key.articleContentJavascriptEnabled: true - ] - - UserDefaults.standard.register(defaults: defaults) - } - - func actualFontSize(for fontSize: FontSize) -> CGFloat { - switch fontSize { - case .small: - return NSFont.systemFontSize - case .medium: - return actualFontSize(for: .small) + 1.0 - case .large: - return actualFontSize(for: .medium) + 4.0 - case .veryLarge: - return actualFontSize(for: .large) + 8.0 - } - } -} - -private extension AppDefaults { - - static var firstRunDate: Date? { - get { - return AppDefaults.date(for: Key.firstRunDate) - } - set { - AppDefaults.setDate(for: Key.firstRunDate, newValue) - } - } - - func fontSize(for key: String) -> FontSize { - // Punted till after 1.0. - return .medium - -// var rawFontSize = int(for: key) -// if rawFontSize < smallestFontSizeRawValue { -// rawFontSize = smallestFontSizeRawValue -// } -// if rawFontSize > largestFontSizeRawValue { -// rawFontSize = largestFontSizeRawValue -// } -// return FontSize(rawValue: rawFontSize)! - } - - static func setFontSize(for key: String, _ fontSize: FontSize) { - setInt(for: key, fontSize.rawValue) - } - - static func string(for key: String) -> String? { - return UserDefaults.standard.string(forKey: key) - } - - static func setString(for key: String, _ value: String?) { - UserDefaults.standard.set(value, forKey: key) - } - - static func bool(for key: String) -> Bool { - return UserDefaults.standard.bool(forKey: key) - } - - static func setBool(for key: String, _ flag: Bool) { - UserDefaults.standard.set(flag, forKey: key) - } - - static func int(for key: String) -> Int { - return UserDefaults.standard.integer(forKey: key) - } - - static func setInt(for key: String, _ x: Int) { - UserDefaults.standard.set(x, forKey: key) - } - - static func date(for key: String) -> Date? { - return UserDefaults.standard.object(forKey: key) as? Date - } - - static func setDate(for key: String, _ date: Date?) { - UserDefaults.standard.set(date, forKey: key) - } - - static func sortDirection(for key: String) -> ComparisonResult { - let rawInt = int(for: key) - if rawInt == ComparisonResult.orderedAscending.rawValue { - return .orderedAscending - } - return .orderedDescending - } -} diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index 60f7892c8..b5e081180 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -37,7 +37,7 @@ let appName = "NetNewsWire" } private var refreshTimer: AccountRefreshTimer? - private var lastRefreshInterval = AppDefaults.shared.refreshInterval + private var lastRefreshInterval = AppDefaults.refreshInterval private var shuttingDown = false { didSet { @@ -53,6 +53,8 @@ let appName = "NetNewsWire" @IBOutlet var debugMenuItem: NSMenuItem! @IBOutlet var useColumnLayoutMenuItem: NSMenuItem? + @IBOutlet var showStatusBarMenuItem: NSMenuItem? + @IBOutlet var showStatusBarThemeMenuMenuItem: NSMenuItem? @IBOutlet var checkForUpdatesMenuItem: NSMenuItem! var unreadCount = 0 { @@ -119,6 +121,7 @@ let appName = "NetNewsWire" NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: AccountManager.shared) NotificationCenter.default.addObserver(self, selector: #selector(handleUnreadCountDisplaySettingDidChange(_:)), name: .unreadCountDisplaySettingDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleUserInterfaceColorPaletteDidUpdate(_:)), name: .userInterfaceColorPaletteDidUpdate, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(inspectableObjectsDidChange(_:)), name: .InspectableObjectsDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(importDownloadedTheme(_:)), name: .didEndDownloadingTheme, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(themeImportError(_:)), name: .didFailToImportThemeWithError, object: nil) @@ -142,23 +145,11 @@ let appName = "NetNewsWire" func applicationWillFinishLaunching(_ notification: Notification) { FaviconGenerator.templateImage = Assets.Images.faviconTemplate + applyUserInterfaceColorPalette() installAppleEventHandlers() CacheCleaner.purgeIfNecessary() - - // Try to establish a cache in the Caches folder, but if it fails for some reason fall back to a temporary dir - let cacheFolder: String - if let userCacheFolder = try? FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false).path { - cacheFolder = userCacheFolder - } else { - let bundleIdentifier = (Bundle.main.infoDictionary!["CFBundleIdentifier"]! as! String) - cacheFolder = (NSTemporaryDirectory() as NSString).appendingPathComponent(bundleIdentifier) - } - - let imagesFolder = (cacheFolder as NSString).appendingPathComponent("Images") - let imagesFolderURL = URL(fileURLWithPath: imagesFolder) - try! FileManager.default.createDirectory(at: imagesFolderURL, withIntermediateDirectories: true, attributes: nil) } func applicationDidFinishLaunching(_ note: Notification) { @@ -192,8 +183,8 @@ let appName = "NetNewsWire" Self.logger.error("Failed to start software updater with error: \(error.localizedDescription)") } - AppDefaults.shared.registerDefaults() - let isFirstRun = AppDefaults.shared.isFirstRun + AppDefaults.registerDefaults() + let isFirstRun = AppDefaults.isFirstRun if isFirstRun { Self.logger.debug("Is first run.") } @@ -204,6 +195,7 @@ let appName = "NetNewsWire" } updateColumnLayoutMenuItem() + updateStatusBarMenuItems() if mainWindowController == nil { let mainWindowController = createAndShowMainWindow() @@ -214,7 +206,6 @@ let appName = "NetNewsWire" mainWindowController?.window?.center() } - NotificationCenter.default.addObserver(self, selector: #selector(feedSettingDidChange(_:)), name: .feedSettingDidChange, object: nil) NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { _ in MainActor.assumeIsolated { self.userDefaultsDidChange() @@ -248,7 +239,6 @@ let appName = "NetNewsWire" ArticleThemesManager.shared.start() NetworkMonitor.shared.start() - MemoryPressureMonitor.shared.start() #if !SKIP_APP_GROUP_ACCESS ExtensionContainersFile.shared.start() @@ -271,7 +261,7 @@ let appName = "NetNewsWire" refreshTimer!.update() ArticleStatusSyncTimer.shared.update() #else - if AppDefaults.shared.suppressSyncOnLaunch { + if AppDefaults.suppressSyncOnLaunch { refreshTimer!.update() ArticleStatusSyncTimer.shared.update() } else { @@ -282,7 +272,7 @@ let appName = "NetNewsWire" } #endif - if !AppDefaults.shared.showDebugMenu { + if !AppDefaults.showDebugMenu { debugMenuItem.menu?.removeItem(debugMenuItem) } @@ -377,15 +367,8 @@ let appName = "NetNewsWire" updateDockBadge() } - @objc func feedSettingDidChange(_ note: Notification) { - MainActor.assumeIsolated { - guard let feed = note.object as? Feed, let key = note.userInfo?[Feed.SettingUserInfoKey] as? Feed.SettingKey else { - return - } - if key == .homePageURL || key == .faviconURL { - _ = FaviconDownloader.shared.favicon(for: feed) - } - } + @objc func handleUserInterfaceColorPaletteDidUpdate(_ notification: Notification) { + applyUserInterfaceColorPalette() } @objc func inspectableObjectsDidChange(_ note: Notification) { @@ -399,10 +382,11 @@ let appName = "NetNewsWire" func userDefaultsDidChange() { updateColumnLayoutMenuItem() + updateStatusBarMenuItems() - if lastRefreshInterval != AppDefaults.shared.refreshInterval { + if lastRefreshInterval != AppDefaults.refreshInterval { refreshTimer?.update() - lastRefreshInterval = AppDefaults.shared.refreshInterval + lastRefreshInterval = AppDefaults.refreshInterval } updateDockBadge() @@ -482,7 +466,7 @@ let appName = "NetNewsWire" let isDisplayingSheet = mainWindowController?.isDisplayingSheet ?? false if item.action == #selector(refreshAll(_:)) { - return !AccountManager.shared.refreshInProgress && !AccountManager.shared.activeAccounts.isEmpty + return AccountManager.shared.canRefresh } if item.action == #selector(importOPMLFromFile(_:)) { @@ -501,8 +485,16 @@ let appName = "NetNewsWire" return AccountManager.shared.hasiCloudAccount } + if item.action == #selector(toggleStatusBarThemeMenu(_:)) { + return AppDefaults.showStatusBar + } + if item.action == #selector(toggleWebInspectorEnabled(_:)) { - (item as! NSMenuItem).state = AppDefaults.shared.webInspectorEnabled ? .on : .off + (item as! NSMenuItem).state = AppDefaults.webInspectorEnabled ? .on : .off + } + + if let isShown = SidebarViewController.smartFeedIsShown(forGoToAction: item.action) { + return isShown } return true @@ -563,7 +555,7 @@ let appName = "NetNewsWire" // MARK: - Dock Badge @objc func updateDockBadge() { Task { @MainActor in - NSApplication.shared.dockTile.badgeLabel = AppDefaults.shared.unreadCountDisplay.text(for: unreadCount) ?? "" + NSApplication.shared.dockTile.badgeLabel = AppDefaults.unreadCountDisplay.text(for: unreadCount) ?? "" } } @@ -762,7 +754,15 @@ let appName = "NetNewsWire" } @IBAction func toggleColumnLayout(_ sender: Any?) { - AppDefaults.shared.useColumnLayout.toggle() + AppDefaults.useColumnLayout.toggle() + } + + @IBAction func toggleStatusBar(_ sender: Any?) { + AppDefaults.showStatusBar.toggle() + } + + @IBAction func toggleStatusBarThemeMenu(_ sender: Any?) { + AppDefaults.showStatusBarThemeMenu.toggle() } @IBAction func checkForUpdates(_ sender: Any?) { @@ -811,13 +811,13 @@ extension AppDelegate { } @IBAction func toggleWebInspectorEnabled(_ sender: Any?) { - let newValue = !AppDefaults.shared.webInspectorEnabled - AppDefaults.shared.webInspectorEnabled = newValue + let newValue = !AppDefaults.webInspectorEnabled + AppDefaults.webInspectorEnabled = newValue // An attached inspector can display incorrectly on certain setups (like mine); default to displaying in a separate window, // and reset the default to a separate window when the preference is toggled off and on again in case the inspector is // accidentally reattached. - AppDefaults.shared.webInspectorStartsAttached = false + AppDefaults.webInspectorStartsAttached = false NotificationCenter.default.post(name: .WebInspectorEnabledDidChange, object: newValue) } @@ -881,7 +881,20 @@ extension AppDelegate { } @MainActor func updateColumnLayoutMenuItem() { - useColumnLayoutMenuItem?.state = AppDefaults.shared.useColumnLayout ? .on : .off + useColumnLayoutMenuItem?.state = AppDefaults.useColumnLayout ? .on : .off + } + + @MainActor func updateStatusBarMenuItems() { + if AppDefaults.showStatusBar { + showStatusBarMenuItem?.title = NSLocalizedString("Hide Status Bar", comment: "Command") + } else { + showStatusBarMenuItem?.title = NSLocalizedString("Show Status Bar", comment: "Command") + } + if AppDefaults.showStatusBarThemeMenu { + showStatusBarThemeMenuMenuItem?.title = NSLocalizedString("Hide Theme Menu in Status Bar", comment: "Command") + } else { + showStatusBarThemeMenuMenuItem?.title = NSLocalizedString("Show Theme Menu in Status Bar", comment: "Command") + } } func importTheme(url: URL) { @@ -1054,6 +1067,17 @@ extension AppDelegate: NSWindowRestoration { private extension AppDelegate { + func applyUserInterfaceColorPalette() { + switch AppDefaults.userInterfaceColorPalette { + case .automatic: + NSApp.appearance = nil + case .light: + NSApp.appearance = NSAppearance(named: .aqua) + case .dark: + NSApp.appearance = NSAppearance(named: .darkAqua) + } + } + func handleMarkAsRead(userInfo: [AnyHashable: Any]) { handleStatusNotification(userInfo: userInfo, statusKey: .read) } diff --git a/Mac/Browser.swift b/Mac/Browser.swift index 63489eb17..862b15e2a 100644 --- a/Mac/Browser.swift +++ b/Mac/Browser.swift @@ -15,7 +15,7 @@ import RSWeb /// The user-assigned default browser, or `nil` if none was assigned /// (i.e., the system default should be used). static var defaultBrowser: MacWebBrowser? { - guard let browserID = AppDefaults.shared.defaultBrowserID else { + guard let browserID = AppDefaults.defaultBrowserID else { return nil } // Older versions stored a bundle ID rather than a path. @@ -33,7 +33,7 @@ import RSWeb /// - invert: Whether to invert the "open in background in browser" preference static func open(_ urlString: String, invertPreference invert: Bool = false) { // Opens according to prefs. - open(urlString, inBackground: invert ? !AppDefaults.shared.openInBrowserInBackground : AppDefaults.shared.openInBrowserInBackground) + open(urlString, inBackground: invert ? !AppDefaults.openInBrowserInBackground : AppDefaults.openInBrowserInBackground) } /// Opens a URL in the default browser. @@ -46,6 +46,12 @@ import RSWeb static func open(_ urlString: String, inBackground: Bool) { guard let url = URL(string: urlString), let preparedURL = url.preparedForOpeningInBrowser() else { return } + // Non-web links (mailto, magnet) go to the system handler, not a browser. + guard preparedURL.isHTTPOrHTTPSURL() else { + NSWorkspace.shared.open(preparedURL) + return + } + let configuration = NSWorkspace.OpenConfiguration() configuration.requiresUniversalLinks = true configuration.promptsUserIfNeeded = false @@ -71,7 +77,7 @@ import RSWeb extension Browser { static var titleForOpenInBrowserInverted: String { - let openInBackgroundPref = AppDefaults.shared.openInBrowserInBackground + let openInBackgroundPref = AppDefaults.openInBrowserInBackground return openInBackgroundPref ? NSLocalizedString("Open in Browser in Foreground", comment: "Open in Browser in Foreground menu item title") : diff --git a/Mac/Dinosaurs/DinosaursWindowController.swift b/Mac/Dinosaurs/DinosaursWindowController.swift index e7994babd..636474c57 100644 --- a/Mac/Dinosaurs/DinosaursWindowController.swift +++ b/Mac/Dinosaurs/DinosaursWindowController.swift @@ -63,8 +63,7 @@ final class DinosaursWindowController: NSWindowController { updateActionBarEnabledState() - NotificationCenter.default.addObserver(self, selector: #selector(handleFaviconDidBecomeAvailable(_:)), name: .FaviconDidBecomeAvailable, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(handleFeedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleFeedIconImageDidChange(_:)), name: .feedIconImageDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleChildrenDidChange(_:)), name: .ChildrenDidChange, object: nil) } @@ -160,11 +159,7 @@ final class DinosaursWindowController: NSWindowController { } } - @objc func handleFaviconDidBecomeAvailable(_ notification: Notification) { - reloadFeedColumn() - } - - @objc func handleFeedIconDidBecomeAvailable(_ notification: Notification) { + @objc func handleFeedIconImageDidChange(_ notification: Notification) { guard let feed = notification.userInfo?[UserInfoKey.feed] as? Feed else { return } diff --git a/Mac/Inspector/FeedInspectorViewController.swift b/Mac/Inspector/FeedInspectorViewController.swift index df1f7cbc7..7b87ed915 100644 --- a/Mac/Inspector/FeedInspectorViewController.swift +++ b/Mac/Inspector/FeedInspectorViewController.swift @@ -53,7 +53,7 @@ final class FeedInspectorViewController: NSViewController, Inspector { override func viewDidLoad() { updateUI() - NotificationCenter.default.addObserver(self, selector: #selector(imageDidBecomeAvailable(_:)), name: .imageDidBecomeAvailable, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleFeedIconImageDidChange(_:)), name: .feedIconImageDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(updateUI), name: .DidUpdateFeedPreferencesFromContextMenu, object: nil) } @@ -114,7 +114,7 @@ final class FeedInspectorViewController: NSViewController, Inspector { // MARK: Notifications - @objc func imageDidBecomeAvailable(_ note: Notification) { + @objc func handleFeedIconImageDidChange(_ notification: Notification) { updateImage() } } diff --git a/Mac/MainMenu/Base.lproj/MainMenu.xib b/Mac/MainMenu/Base.lproj/MainMenu.xib index 89e292ff2..839534a34 100644 --- a/Mac/MainMenu/Base.lproj/MainMenu.xib +++ b/Mac/MainMenu/Base.lproj/MainMenu.xib @@ -1,7 +1,7 @@ - + - + @@ -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 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -149,7 +73,7 @@ - + @@ -177,7 +101,7 @@ - + @@ -188,7 +112,7 @@ - + @@ -203,7 +127,7 @@ - + @@ -239,7 +163,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<UInt8>, 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<UInt8>, 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<ParsedAuthor> = [] - var attachments: Set<ParsedAttachment> = [] + 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<ParsedAuthor>, avatarURLs: Set<String>) { + var avatarURLs = Set<String>() + 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 `<enclosure>` 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 (<s:variant>, 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 `<img>` 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 `<picture>`, 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..<offset]) + result.append(contentsOf: attributeBytes) + copyStart = offset + } + result.append(contentsOf: bytes[copyStart...]) + return String(decoding: result, as: UTF8.self) + } +} + +// MARK: - Delegate + +private final class InserterDelegate: HTMLScannerDelegate { + + private let urlString: String + private let baseURL: URL? + private(set) var insertionOffsets = [Int]() // Just past each matching tag name + private var pictureDepth = 0 + + private static let imgBytes: [UInt8] = Array("img".utf8) + private static let pictureBytes: [UInt8] = Array("picture".utf8) + + init(urlString: String, baseURL: URL?) { + self.urlString = urlString + self.baseURL = baseURL + } + + func htmlScanner(_ scanner: HTMLScanner, didStartTag name: ArraySlice<UInt8>, 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<UInt8>) { + 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 `<img>`s in an HTML document that pass `SignificantImageFilter`, +/// which also sees the enclosing `<a>` 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<UInt8>, + 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<UInt8>) { + 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<String> { + 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 `<a>` element harvested from an HTML document. +// A single `<a>` 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<UInt8>, attributes: HTMLAttributes, selfClosing: Bool) { - if finished { + // Nothing after <body> 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<UInt8>, _ 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 `<script>` and `<style>` treated as opaque raw text: only -// the matching `</script>` / `</style>` ends the block. +// - Content of `<script>`, `<style>`, `<textarea>`, `<title>`, `<xmp>`, and +// `<noembed>` treated as opaque raw text: only the matching end tag ends +// the block. Entities are expanded only in `<textarea>` and `<title>`, as in HTML. // - Attributes may have no value (`<input disabled>`), single-quoted values, // or unquoted values (`<a href=foo>`). -// - No void-element tracking. Consumers that care (both of ours don't) +// - No void-element tracking. Consumers that care (none of ours do) // apply their own void-element list at the delegate level. // // Not re-entrant. Callbacks happen on the thread that called `parse(_:)`. @@ -25,21 +26,26 @@ public final class HTMLScanner { public weak var delegate: HTMLScannerDelegate? + private var input: [UInt8] = [] + private var pos: Int = 0 + private var stopped = false + public init(delegate: HTMLScannerDelegate) { self.delegate = delegate } public func parse(_ bytes: [UInt8]) { - self.input = bytes - self.pos = 0 + input = bytes + pos = 0 + stopped = false drive() delegate?.htmlScannerDidEnd(self) } - // MARK: - Private state - - private var input: [UInt8] = [] - private var pos: Int = 0 + /// Ends parsing after the current delegate callback returns. + public func stopParsing() { + stopped = true + } } // MARK: - Private @@ -47,12 +53,12 @@ public final class HTMLScanner { private extension HTMLScanner { // Tag names that enter raw-text mode. Their content isn't parsed as markup; - // only the matching </script> or </style> 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 <script> and <style>. - if !selfClosing { - if tagNameEqualsIgnoringCase(nameSlice, Self.scriptBytes[...]) { - consumeRawText(until: Self.scriptBytes[...]) - } else if tagNameEqualsIgnoringCase(nameSlice, Self.styleBytes[...]) { - consumeRawText(until: Self.styleBytes[...]) - } + if !selfClosing, let rawTextTagName = Self.rawTextTagNames.first(where: { Self.tagNameEqualsIgnoringCase(nameSlice, $0[...]) }) { + consumeRawText(until: rawTextTagName[...], decodesEntities: Self.escapableRawTextTagNames.contains(rawTextTagName)) } } @@ -271,12 +272,12 @@ private extension HTMLScanner { delegate?.htmlScanner(self, didEndTag: nameSlice) } - // MARK: - Script / style raw text + // MARK: - Raw text - /// In raw-text mode after a `<script>` or `<style>` start tag, scan forward + /// In raw-text mode after a start tag in `rawTextTagNames`, scan forward /// until the matching end tag `</name>` (case-insensitive) and emit the /// accumulated bytes as characters, followed by the end tag. - func consumeRawText(until tagName: ArraySlice<UInt8>) { + func consumeRawText(until tagName: ArraySlice<UInt8>, decodesEntities: Bool) { let start = pos while pos < input.count { if input[pos] == .asciiLessThan && peek(1) == .asciiSlash { @@ -287,9 +288,9 @@ private extension HTMLScanner { nameEnd += 1 } let candidateName = input[closerStart..<nameEnd] - if tagNameEqualsIgnoringCase(candidateName, tagName) { + if Self.tagNameEqualsIgnoringCase(candidateName, tagName) { if start < savedPos { - delegate?.htmlScanner(self, didFindCharacters: input[start..<savedPos]) + emitRawText(start..<savedPos, decodesEntities: decodesEntities) } pos = nameEnd while pos < input.count && input[pos] != .asciiGreaterThan { @@ -306,10 +307,31 @@ private extension HTMLScanner { } // EOF without closer — flush what we have as characters. if start < pos { - delegate?.htmlScanner(self, didFindCharacters: input[start..<pos]) + emitRawText(start..<pos, decodesEntities: decodesEntities) } } + func emitRawText(_ range: Range<Int>, decodesEntities: Bool) { + guard decodesEntities, input[range].contains(.asciiAmpersand) else { + delegate?.htmlScanner(self, didFindCharacters: input[range]) + return + } + var out = [UInt8]() + out.reserveCapacity(range.count) + var index = range.lowerBound + while index < range.upperBound { + if input[index] == .asciiAmpersand { + let result = XMLEntities.decode(bytes: input, at: index, mode: .html) + out.append(contentsOf: result.bytes) + index = max(result.nextIndex, index + 1) + continue + } + out.append(input[index]) + index += 1 + } + delegate?.htmlScanner(self, didFindCharacters: out[...]) + } + // MARK: - Character data func scanCharacters() { @@ -461,8 +483,11 @@ private extension HTMLScanner { return true } } +} - func tagNameEqualsIgnoringCase(_ a: ArraySlice<UInt8>, _ b: ArraySlice<UInt8>) -> Bool { +extension HTMLScanner { + + static func tagNameEqualsIgnoringCase(_ a: ArraySlice<UInt8>, _ b: ArraySlice<UInt8>) -> Bool { guard a.count == b.count else { return false } diff --git a/Modules/RSParser/Sources/RSParser/HTML/SignificantImageFilter.swift b/Modules/RSParser/Sources/RSParser/HTML/SignificantImageFilter.swift new file mode 100644 index 000000000..2b9fc79ba --- /dev/null +++ b/Modules/RSParser/Sources/RSParser/HTML/SignificantImageFilter.swift @@ -0,0 +1,144 @@ +// +// SignificantImageFilter.swift +// RSParser +// +// Created by Brent Simmons on 10/25/26. +// + +import Foundation + +/// Rejects images that can’t stand for an article: tracking pixels, smileys, +/// emoji, badges, share buttons, avatars, and banner-shaped strips. +/// Share buttons are recognized by their enclosing link, since the icons +/// themselves are often hosted on the blog’s own server. +/// +/// Undeclared dimensions pass, since most images in feeds don’t declare them. +/// Callers that later learn the real dimensions check them with `hasSignificantDimensions`. +public enum SignificantImageFilter { + + public static let minimumDimension = 64 + public static let maximumAspectRatio = 6.0 + + /// `htmlClass` is an `<img>` tag’s `class` attribute. `enclosingLinkURLString` is the `href` of the `<a>` it’s inside. + public static func isSignificant(urlString: String, width: Int?, height: Int?, htmlClass: String? = nil, enclosingLinkURLString: String? = nil) -> Bool { + hasSignificantDimensions(width: width, height: height) && !isBlockedURL(urlString) && !hasDecorativeClass(htmlClass) && !isSharingLink(enclosingLinkURLString) + } + + public static func hasSignificantDimensions(width: Int?, height: Int?) -> Bool { + if let width, width < minimumDimension { + return false + } + if let height, height < minimumDimension { + return false + } + if let width, let height { + let aspectRatio = Double(max(width, height)) / Double(min(width, height)) + if aspectRatio > maximumAspectRatio { + return false + } + } + return true + } +} + +private extension SignificantImageFilter { + + typealias HostAndPathPrefix = (host: String, pathPrefix: String) + + static let decorativeClasses: Set<String> = ["emoji", "wp-smiley"] + + /// File names, without extension, of tracking pixels and placeholders on any host. Lowercase. + static let blockedFileNames: Set<String> = ["1x1", "blank", "pixel", "spacer", "transparent"] + + /// Path components of open-tracking and click-tracking URLs on any host. Lowercase. + static let blockedPathComponents: Set<String> = ["open", "track"] + + /// A URL ending in one of these isn’t blocked by its path components. GIF isn’t included, since it’s the usual format for tracking pixels. + static let photoFileExtensions: Set<String> = ["avif", "heic", "jpeg", "jpg", "png", "webp"] + + /// Share buttons, badges, tracking pixels, and placeholders. Hosts include their subdomains. Path prefixes are lowercase. + static let blockedImagePrefixes: [HostAndPathPrefix] = [ + (host: "addtoany.com", pathPrefix: "/"), + (host: "feedburner.com", pathPrefix: "/"), + (host: "feeds.wordpress.com", pathPrefix: "/"), + (host: "pixel.wp.com", pathPrefix: "/"), + (host: "s.w.org", pathPrefix: "/images/core/emoji/"), + (host: "s0.wp.com", pathPrefix: "/i/blank.jpg"), + (host: "stats.wordpress.com", pathPrefix: "/") + ] + + /// Share endpoints. Hosts include their subdomains. Path prefixes are lowercase. + static let sharingLinkPrefixes: [HostAndPathPrefix] = [ + (host: "addtoany.com", pathPrefix: "/"), + (host: "bsky.app", pathPrefix: "/intent/"), + (host: "digg.com", pathPrefix: "/submit"), + (host: "facebook.com", pathPrefix: "/dialog/"), + (host: "facebook.com", pathPrefix: "/share"), + (host: "flipboard.com", pathPrefix: "/bookmarklet"), + (host: "getpocket.com", pathPrefix: "/save"), + (host: "linkedin.com", pathPrefix: "/cws/share"), + (host: "linkedin.com", pathPrefix: "/sharearticle"), + (host: "linkedin.com", pathPrefix: "/sharing/"), + (host: "news.ycombinator.com", pathPrefix: "/submitlink"), + (host: "pinterest.com", pathPrefix: "/pin/create"), + (host: "reddit.com", pathPrefix: "/submit"), + (host: "shareaholic.com", pathPrefix: "/"), + (host: "sharethis.com", pathPrefix: "/"), + (host: "t.me", pathPrefix: "/share"), + (host: "threads.net", pathPrefix: "/intent/"), + (host: "tumblr.com", pathPrefix: "/share"), + (host: "tumblr.com", pathPrefix: "/widgets/share"), + (host: "twitter.com", pathPrefix: "/intent/"), + (host: "twitter.com", pathPrefix: "/share"), + (host: "whatsapp.com", pathPrefix: "/send"), + (host: "x.com", pathPrefix: "/intent/"), + (host: "x.com", pathPrefix: "/share") + ] + + static func isBlockedURL(_ urlString: String) -> Bool { + guard let url = URL(string: urlString), let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else { + return true + } + guard let host = url.host()?.lowercased() else { + return true + } + if url.pathExtension.lowercased() == "svg" { + return true + } + if blockedFileNames.contains(url.deletingPathExtension().lastPathComponent.lowercased()) { + return true + } + if !photoFileExtensions.contains(url.pathExtension.lowercased()), url.pathComponents.contains(where: { blockedPathComponents.contains($0.lowercased()) }) { + return true + } + if matches(host: host, path: url.path().lowercased(), blockedImagePrefixes) { + return true + } + return MediaRSS.isGravatar(url) + } + + /// Includes `mailto:` links, the usual target of an email-this-article button. + static func isSharingLink(_ urlString: String?) -> Bool { + guard let urlString, let url = URL(string: urlString), let scheme = url.scheme?.lowercased() else { + return false + } + if scheme == "mailto" { + return true + } + guard let host = url.host()?.lowercased() else { + return false + } + return matches(host: host, path: url.path().lowercased(), sharingLinkPrefixes) + } + + static func matches(host: String, path: String, _ prefixes: [HostAndPathPrefix]) -> Bool { + prefixes.contains { (host == $0.host || host.hasSuffix("." + $0.host)) && path.hasPrefix($0.pathPrefix) } + } + + static func hasDecorativeClass(_ htmlClass: String?) -> Bool { + guard let htmlClass else { + return false + } + return htmlClass.split(whereSeparator: \.isWhitespace).contains { decorativeClasses.contains($0.lowercased()) } + } +} diff --git a/Modules/RSParser/Sources/RSParser/XML/XMLAttributes.swift b/Modules/RSParser/Sources/RSParser/XML/XMLAttributes.swift index 1719c28fb..7fc065fd0 100644 --- a/Modules/RSParser/Sources/RSParser/XML/XMLAttributes.swift +++ b/Modules/RSParser/Sources/RSParser/XML/XMLAttributes.swift @@ -60,13 +60,12 @@ public struct XMLAttributes: Sendable { value(forName: name, caseInsensitive: false) } - /// Case-insensitive qualified-name lookup — for RSS authors who mess up attribute - /// casing (`isPermaLink` vs `ispermalink`). - public func value(forNameCaseInsensitive name: String) -> String? { + /// For feeds with messed up casing (`isPermaLink` vs `ispermalink`). + public func value(forCaseInsensitiveName name: String) -> String? { value(forName: name, caseInsensitive: true) } - /// Materialize a `[String: String]` dictionary of qualified names → values. + /// Create dictionary of qualified names to values. public func dictionary() -> [String: String] { var dict = [String: String]() dict.reserveCapacity(attributes.count) diff --git a/Modules/RSParser/Sources/RSParser/XML/XMLNamespace.swift b/Modules/RSParser/Sources/RSParser/XML/XMLNamespace.swift index 38a694111..e3c7b7469 100644 --- a/Modules/RSParser/Sources/RSParser/XML/XMLNamespace.swift +++ b/Modules/RSParser/Sources/RSParser/XML/XMLNamespace.swift @@ -49,7 +49,7 @@ public struct XMLNamespace: Sendable, Equatable, Hashable { } public var isMediaRSS: Bool { - uri == URI.mediaRSS + uri == URI.mediaRSS || uri == URI.mediaRSSBoard } public var isITunes: Bool { @@ -71,6 +71,7 @@ public struct XMLNamespace: Sendable, Equatable, Hashable { public static let content = "http://purl.org/rss/1.0/modules/content/" public static let xhtml = "http://www.w3.org/1999/xhtml" public static let mediaRSS = "http://search.yahoo.com/mrss/" + public static let mediaRSSBoard = "http://www.rssboard.org/media-rss" public static let itunes = "http://www.itunes.com/dtds/podcast-1.0.dtd" public static let source = "https://source.scripting.com/" } diff --git a/Modules/RSParser/Tests/RSParserTests/Feeds/JSON/JSONFeedParserTests.swift b/Modules/RSParser/Tests/RSParserTests/Feeds/JSON/JSONFeedParserTests.swift index 8187d32d1..de6ee6c49 100644 --- a/Modules/RSParser/Tests/RSParserTests/Feeds/JSON/JSONFeedParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/Feeds/JSON/JSONFeedParserTests.swift @@ -98,4 +98,22 @@ import RSParser let bothAuthorsItem = try #require(parsedFeed.items.first { $0.uniqueID == "Item with both" }) #expect(bothAuthorsItem.authors == itemAuthors) } + + @Test func attachments() throws { + let d = parserData("attachments", "json", "https://example.com/") + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + let attachments = try #require(item.attachments) + #expect(attachments.count == 2) + + let audio = try #require(attachments.first { $0.url == "https://example.com/episode1.mp3" }) + #expect(audio.mimeType == "audio/mpeg") + #expect(audio.title == "Episode 1") + #expect(audio.sizeInBytes == 12345678) + #expect(audio.durationInSeconds == 3600) + + // mime_type is optional in the JSON Feed spec. + let image = try #require(attachments.first { $0.url == "https://example.com/episode1.jpg" }) + #expect(image.mimeType == nil) + } } diff --git a/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift b/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift index 5427b6104..58df54769 100644 --- a/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift @@ -650,4 +650,26 @@ import RSParser let item = try #require(parsedFeed.items.first { $0.uniqueID == "https://draw-down.com/products/9225111929086" }) #expect(item.title == "Revue Faire — no. 56 (Reading Until I Sleep: Manuel Raeder)") } + + @Test func youTubeMediaGroup() throws { + let d = parserData("youtube", "atom", "https://www.youtube.com/feeds/videos.xml?channel_id=UCexamplechannel000000") + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + + #expect(item.title == "Real Video Title") + #expect(item.url == "https://www.youtube.com/watch?v=abcdefghijk") + #expect(item.thumbnailURL == "https://i1.ytimg.com/vi/abcdefghijk/hqdefault.jpg") + + // No content or summary, so the plain-text media:description is the body. + #expect(item.contentHTML == nil) + #expect(item.contentText == "The video’s description.") + + let attachments = try #require(item.attachments) + #expect(attachments.count == 1) + let attachment = try #require(attachments.first) + #expect(attachment.url == "https://www.youtube.com/v/abcdefghijk?version=3") + #expect(attachment.mimeType == "application/x-shockwave-flash") + #expect(attachment.width == 640) + #expect(attachment.height == 390) + } } diff --git a/Modules/RSParser/Tests/RSParserTests/Feeds/XML/RSSParserTests.swift b/Modules/RSParser/Tests/RSParserTests/Feeds/XML/RSSParserTests.swift index d92862e71..3e04fdffc 100644 --- a/Modules/RSParser/Tests/RSParserTests/Feeds/XML/RSSParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/Feeds/XML/RSSParserTests.swift @@ -33,9 +33,134 @@ import RSParser #expect(size >= 22275279) } #expect(attachment.mimeType == "audio/mpeg") + #expect(attachment.durationInSeconds != nil) } } + @Test func atpEnclosureAndMediaContentMerged() throws { + // Each atp.fm item has the same file as both <enclosure> and <media:content>. + let d = parserData("atp", "rss", "http://atp.fm/") + let parsedFeed = try #require(try FeedParser.parse(d)) + #expect(parsedFeed.items.count == 100) + + for article in parsedFeed.items { + let attachments = try #require(article.attachments) + #expect(attachments.count == 1) + let attachment = try #require(attachments.first) + // Some items have no type attribute, only medium. + #expect(attachment.medium == .audio) + #expect(attachment.sizeInBytes != nil) + } + + let article = try #require(parsedFeed.items.first { $0.title == "311: Mutually Assured Destruction" }) + let attachment = try #require(article.attachments?.first) + #expect(attachment.url == "http://traffic.libsyn.com/atpfm/atp311.mp3") + #expect(attachment.mimeType == "audio/mpeg") + #expect(attachment.sizeInBytes == 54919661) + #expect(attachment.durationInSeconds == 6849) // itunes:duration 01:54:09 + #expect(article.imageURL == "http://static1.squarespace.com/static/513abd71e4b0fe58c655c105/t/52c45a37e4b0a77a5034aa84/1388599866232/1500w/Artwork.jpg") // itunes:image + } + + @Test func cloudBlogMediaContentImages() throws { + let d = parserData("cloudblog", "rss", "https://cloud.google.com/blog/") + let parsedFeed = try #require(try FeedParser.parse(d)) + + let articlesWithAttachments = parsedFeed.items.filter { $0.attachments != nil } + #expect(articlesWithAttachments.count == 18) + for article in articlesWithAttachments { + let attachments = try #require(article.attachments) + #expect(attachments.count == 1) + let attachment = try #require(attachments.first) + #expect(attachment.url.hasPrefix("https://storage.googleapis.com/")) + #expect(attachment.width != nil) + #expect(attachment.height != nil) + } + } + + @Test func mediaGroupKeepsDefaultRendition() throws { + let d = parserData("media-group", "rss", "https://example.com/feed") + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + + #expect(item.title == "Real Article Title") + #expect(item.thumbnailURL == "https://example.com/videos/1.jpg") + + let attachments = try #require(item.attachments) + #expect(attachments.count == 1) + let attachment = try #require(attachments.first) + #expect(attachment.url == "https://example.com/videos/1-high.mp4") + #expect(attachment.mimeType == "video/mp4") + #expect(attachment.medium == .video) + #expect(attachment.width == 1920) + #expect(attachment.height == 1080) + #expect(attachment.durationInSeconds == 125) + } + + @Test func guardianImageRenditionsMergedIntoWidest() throws { + // The Guardian lists each image at widths 140, 460, and 700, as sibling media:content elements. + let rss = """ + <?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title>The Guardianhttps://www.theguardian.com/uk‘A global political awakening’: how gen Z protests are sweeping the worldhttps://www.theguardian.com/world/2026/nov/06/gen-z-protests-sweeping-the-world<p>From Serbia to Bangladesh and India to France, young people are pushing back against authoritarianism</p>https://www.theguardian.com/world/2026/nov/06/gen-z-protests-sweeping-the-worldPhotograph: Uros Arsic/ReutersPhotograph: Uros Arsic/ReutersPhotograph: Uros Arsic/Reuters + """ + let d = ParserData(url: "https://www.theguardian.com/uk/rss", data: Data(rss.utf8)) + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + + let attachments = try #require(item.attachments) + #expect(attachments.count == 1) + let attachment = try #require(attachments.first) + #expect(attachment.url == "https://i.guim.co.uk/img/media/d8c802e22e952ef416894c5d0a6ecca11d13b496/459_0_4582_3666/master/4582.jpg?width=700&quality=85&auto=format&fit=max&s=0e6444e5dfc451bcc781cb563d8ef201") + #expect(attachment.width == 700) + } + + @Test func gravatarBecomesAuthorAvatar() throws { + // WordPress adds the author’s Gravatar as a media:content titled with the author’s name. + let d = parserData("postpunkmonk", "rss", "https://postpunkmonk.com/") + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first { $0.title?.hasPrefix("Automatic Honor") == true }) + + let author = try #require(item.authors?.first) + #expect(author.name == "postpunkmonk") + #expect(author.avatarURL == "https://0.gravatar.com/avatar/fb95b7a51c1ce5897b406c1e656c6eb5f1ecfb4f537d200249ad0c3c53d6b7a1?s=96&d=&r=PG") + + // In feed order. + let attachmentURLs = try #require(item.attachments).map { $0.url } + #expect(attachmentURLs == [ + "https://postpunkmonk.com/wp-content/uploads/2026/10/automatic-shadowplay.jpg", + "https://postpunkmonk.com/wp-content/uploads/2026/10/automatic40eulogy9-26.jpg", + "https://postpunkmonk.com/wp-content/uploads/2022/10/8-ball-yes.jpg" + ]) + } + + @Test func gravatarTitledWithUsernameBecomesAuthorAvatar() throws { + // Hal Mueller’s Blog: the Gravatar’s media:title is the username, which differs from dc:creator. + let gravatarURL = "https://2.gravatar.com/avatar/559e1cc83bb53cbd383cae605e1d28f720da7c925008e6c24eef5e0258f36878?s=96&d=https%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif&r=G" + let rss = """ + Hal Mueller's Bloghttps://halmueller.wordpress.comelectionhttps://halmueller.wordpress.com/2024/11/06/election/http://halmueller.wordpress.com/?p=148halmueller + """ + let d = ParserData(url: "https://halmueller.wordpress.com/feed/", data: Data(rss.utf8)) + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + + let author = try #require(item.authors?.first) + #expect(author.name == "Hal Mueller") + #expect(author.avatarURL == gravatarURL) + #expect(item.attachments == nil) + } + + @Test func feedImageEnclosureIsSkipped() throws { + // Letters from an American: Substack lists the feed’s image as the enclosure of a post with no image of its own. + let feedImageURL = "https://substackcdn.com/image/fetch/$s_!yKDv!,w_256,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4b47f775-3df7-41dd-8bc9-a64cdd72d948_600x600.png" + let rss = """ + Letters from an Americanhttps://heathercoxrichardson.substack.com\(feedImageURL)Letters from an Americanhttps://heathercoxrichardson.substack.comNovember 8, 2026https://heathercoxrichardson.substack.com/p/november-8-2026https://heathercoxrichardson.substack.com/p/november-8-2026Since the dramatic victories of the Democrats on Tuesday, Trump has been posting increasingly provocative material on social media. + """ + let d = ParserData(url: "https://heathercoxrichardson.substack.com/feed", data: Data(rss.utf8)) + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + + #expect(parsedFeed.iconURL == feedImageURL) + #expect(item.attachments == nil) + } + @Test func theOmniShowUniqueIDs() throws { let d = parserData("theomnishow", "rss", "https://theomnishow.omnigroup.com/") let parsedFeed = try #require(try FeedParser.parse(d)) diff --git a/Modules/RSParser/Tests/RSParserTests/HTML/HTMLImageAttributeInserterTests.swift b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLImageAttributeInserterTests.swift new file mode 100644 index 000000000..8068e2195 --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLImageAttributeInserterTests.swift @@ -0,0 +1,36 @@ +// +// HTMLImageAttributeInserterTests.swift +// RSParserTests +// +// Created by Brent Simmons on 10/27/26. +// + +import Foundation +import Testing +import RSParser + +@Suite struct HTMLImageAttributeInserterTests { + + @Test func attributesAreInsertedIntoImagesWhoseSourceResolvesToURL() { + let html = """ +

    Café

    Photo\ + \ + + """ + let result = HTMLImageAttributeInserter.insertingAttributes(" src=\"nnw:x\"", intoImagesWithSource: "https://example.com/images/photo.jpg", html: html, baseURL: URL(string: "https://example.com/2026/10/post.html")) + + let expected = """ +

    Café

    Photo\ + \ + + """ + #expect(result == expected) + } + + @Test func imagesWrittenAsTextInTextareaAreLeftAlone() { + let html = #""# + let result = HTMLImageAttributeInserter.insertingAttributes(" src=\"nnw:x\"", intoImagesWithSource: "https://example.com/images/photo.jpg", html: html, baseURL: URL(string: "https://example.com/")) + + #expect(result == #""#) + } +} diff --git a/Modules/RSParser/Tests/RSParserTests/HTML/HTMLImageParserTests.swift b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLImageParserTests.swift new file mode 100644 index 000000000..4be7d6d4c --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLImageParserTests.swift @@ -0,0 +1,180 @@ +// +// HTMLImageParserTests.swift +// RSParserTests +// +// Created by Brent Simmons on 10/25/26. +// + +import Foundation +import Testing +import RSParser + +@Suite struct HTMLImageParserTests { + + @Test func smileysAreSkipped() throws { + let parsedFeed = try #require(try FeedParser.parse(parserData("natasha", "xml", "https://www.natashatherobot.com/feed/"))) + var foundImageCount = 0 + + for item in parsedFeed.items { + guard let html = item.contentHTML else { + continue + } + let urlString = HTMLImageParser.significantImageURLStrings(html: html, baseURL: URL(string: item.url ?? ""), maximumCount: 1).first + if let urlString { + foundImageCount += 1 + #expect(!urlString.contains("s.w.org")) + } + if item.url == "https://www.natashatherobot.com/url-apple-wallet-passkit-pass/" { + // The first image is 503×88, too wide to stand for the article. + #expect(urlString == "https://www.natashatherobot.com/wp-content/uploads/Screen-Shot-2017-07-07-at-12.35.13-PM.png") + } + } + + #expect(foundImageCount > 0) + } + + @Test func feedBurnerFlaresAndTrackingPixelAreSkipped() { + let html = """ +

    Text.

    +
    + +
    + + """ + #expect(firstSignificantImageURLString(html) == nil) + } + + @Test func hiddenImagesAreSkipped() { + let html = """ + + + + + + """ + #expect(firstSignificantImageURLString(html) == "https://example.com/real.jpg") + } + + @Test func shareButtonsAreSkipped() { + let html = """ + + + """ + #expect(firstSignificantImageURLString(html) == "https://example.com/photo.jpg") + } + + @Test func trackingPixelWithDeclaredDimensionsIsSkipped() { + let html = """ + + + """ + #expect(firstSignificantImageURLString(html) == "https://example.com/photo.jpg") + } + + @Test func imageWithUndeclaredDimensionsIsAccepted() { + // Real dimensions are checked at download time. + let html = #""# + #expect(firstSignificantImageURLString(html) == "https://example.com/photo.jpg") + } + + @Test func gravatarIsSkipped() { + let html = """ + + + """ + #expect(firstSignificantImageURLString(html) == "https://example.com/photo.jpg") + } + + @Test func srcsetIsUsedWhenSrcIsPlaceholder() { + let html = """ + + """ + #expect(firstSignificantImageURLString(html) == "https://example.com/a-1024.jpg") + } + + @Test func srcsetIsUsedBeforeSrc() { + let html = #""# + #expect(firstSignificantImageURLString(html) == "https://example.com/real-800.jpg") + } + + @Test func srcsetUsesNarrowestCandidateWideEnoughForThumbnail() { + let html = #""# + #expect(firstSignificantImageURLString(html) == "https://example.com/a-1536.jpg") + } + + @Test func srcsetDescriptorCanEndWithNewlineOrHaveHeight() { + let htmlWithNewlines = """ + + """ + #expect(firstSignificantImageURLString(htmlWithNewlines) == "https://example.com/a-800.jpg") + + let htmlWithHeights = #""# + #expect(firstSignificantImageURLString(htmlWithHeights) == "https://example.com/a-800.jpg") + } + + @Test func lazySourceIsUsedWhenSrcIsPlaceholder() { + let html = """ + + + """ + #expect(firstSignificantImageURLString(html) == "https://example.com/uploads/photo.jpg") + } + + @Test func lazySrcsetAndOriginalAreUsedWhenSrcIsPlaceholder() { + let placeholder = "data:image/gif;base64,R0lGODlhAQABAAAAACw=" + #expect(firstSignificantImageURLString(#""#) == "https://example.com/a-800.jpg") + #expect(firstSignificantImageURLString(#""#) == "https://example.com/b-800.jpg") + #expect(firstSignificantImageURLString(#""#) == "https://example.com/c.jpg") + } + + @Test func significantImageURLStringsAreFoundUpToMaximumCount() { + let html = """ + + """ + let urlStrings = HTMLImageParser.significantImageURLStrings(html: html, baseURL: URL(string: "https://example.com/posts/1"), maximumCount: 2) + #expect(urlStrings == ["https://example.com/a.jpg", "https://example.com/b.jpg"]) + } + + @Test func relativeURLsAreResolved() { + #expect(firstSignificantImageURLString(#""#) == "https://example.com/posts/images/a.jpg") + #expect(firstSignificantImageURLString(#""#) == "https://cdn.example.net/a.jpg") + } + + @Test func relativeURLIsSkippedWithoutBaseURL() { + let html = #""# + let urlStrings = HTMLImageParser.significantImageURLStrings(html: html, baseURL: nil, maximumCount: 3) + #expect(urlStrings == ["https://example.com/b.jpg"]) + } + + @Test func dimensionsInPixelsAreParsed() { + // The 1px height is too small. The 50% width isn’t in pixels, so it doesn’t count toward the aspect ratio. + let html = #""# + #expect(firstSignificantImageURLString(html) == "https://example.com/b.jpg") + } + + @Test func decorativeURLsAreRejected() { + #expect(!SignificantImageFilter.isSignificant(urlString: "https://example.com/logo.svg", width: nil, height: nil)) + #expect(!SignificantImageFilter.isSignificant(urlString: "https://s0.wp.com/i/blank.jpg", width: nil, height: nil)) + #expect(!SignificantImageFilter.isSignificant(urlString: "https://pixel.wp.com/b.gif?v=1", width: nil, height: nil)) + #expect(!SignificantImageFilter.isSignificant(urlString: "ftp://example.com/a.jpg", width: nil, height: nil)) + #expect(!SignificantImageFilter.isSignificant(urlString: "https://example.com/banner.jpg", width: 1200, height: 150)) + #expect(!SignificantImageFilter.isSignificant(urlString: "https://example.com/images/spacer.gif", width: nil, height: nil)) + #expect(!SignificantImageFilter.isSignificant(urlString: "https://email.example.net/open/abc123.gif", width: nil, height: nil)) + #expect(!SignificantImageFilter.isSignificant(urlString: "https://email.example.net/wf/open?upn=abc123", width: nil, height: nil)) + #expect(SignificantImageFilter.isSignificant(urlString: "https://cdn.example.com/track/cover.jpg", width: nil, height: nil)) + #expect(SignificantImageFilter.isSignificant(urlString: "https://example.com/2026/open-source-pixel-art.jpg", width: nil, height: nil)) + } +} + +// MARK: - Helpers + +private func firstSignificantImageURLString(_ html: String) -> String? { + HTMLImageParser.significantImageURLStrings(html: html, baseURL: URL(string: "https://example.com/posts/1"), maximumCount: 1).first +} diff --git a/Modules/RSParser/Tests/RSParserTests/HTML/HTMLLinkTests.swift b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLLinkTests.swift index eb8e9c6ab..b08bfac7d 100644 --- a/Modules/RSParser/Tests/RSParserTests/HTML/HTMLLinkTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLLinkTests.swift @@ -145,4 +145,11 @@ import RSParser #expect(!u.contains("&"), "entity not decoded in href: \(u)") } } + + @Test func entitiesInSVGTitleInLinkTextDecoded() { + let html = #"News & Notes"# + let d = ParserData(url: "http://example.com/", data: Data(html.utf8)) + let links = HTMLLinkParser.htmlLinks(with: d) + #expect(links.first?.text == "News & Notes") + } } diff --git a/Modules/RSParser/Tests/RSParserTests/Resources/attachments.json b/Modules/RSParser/Tests/RSParserTests/Resources/attachments.json new file mode 100644 index 000000000..b31f98cb3 --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/Resources/attachments.json @@ -0,0 +1,22 @@ +{ + "version": "https://jsonfeed.org/version/1.1", + "title": "Attachments test feed", + "items": [ + { + "id": "Episode 1", + "content_html": "

    Show notes.

    ", + "attachments": [ + { + "url": "https://example.com/episode1.mp3", + "mime_type": "audio/mpeg", + "title": "Episode 1", + "size_in_bytes": 12345678, + "duration_in_seconds": 3600 + }, + { + "url": "https://example.com/episode1.jpg" + } + ] + } + ] +} diff --git a/Modules/RSParser/Tests/RSParserTests/Resources/media-group.rss b/Modules/RSParser/Tests/RSParserTests/Resources/media-group.rss new file mode 100644 index 000000000..d1912d0ca --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/Resources/media-group.rss @@ -0,0 +1,20 @@ + + + +Media Group Test Feed +https://example.com + +Real Article Title +https://example.com/videos/1 +https://example.com/videos/1 + +Media Title + +Unprefixed Title Inside media:content + + + + + + + diff --git a/Modules/RSParser/Tests/RSParserTests/Resources/postpunkmonk.rss b/Modules/RSParser/Tests/RSParserTests/Resources/postpunkmonk.rss new file mode 100644 index 000000000..4f5cb2815 --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/Resources/postpunkmonk.rss @@ -0,0 +1,695 @@ + + + + Post-Punk Monk + + https://postpunkmonk.com + Searching for divinity in records from '78-'85 or so… + Fri, 23 Oct 2026 19:10:15 +0000 + en + + hourly + + 1 + http://wordpress.com/ + + + https://postpunkmonk.com/wp-content/uploads/2013/09/ppm-avatar.jpg?w=32 + Post-Punk Monk + https://postpunkmonk.com + 32 + 32 + +15133602 +https://postpunkmonk.com/?rsscloud=notify + + diff --git a/Modules/RSParser/Tests/RSParserTests/Resources/youtube.atom b/Modules/RSParser/Tests/RSParserTests/Resources/youtube.atom new file mode 100644 index 000000000..c192573e8 --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/Resources/youtube.atom @@ -0,0 +1,36 @@ + + + + yt:channel:examplechannel000000 + examplechannel000000 + Example Channel + + + Example Channel + https://www.youtube.com/channel/UCexamplechannel000000 + + 2020-01-01T00:00:00+00:00 + + yt:video:abcdefghijk + abcdefghijk + UCexamplechannel000000 + Real Video Title + + + Example Channel + https://www.youtube.com/channel/UCexamplechannel000000 + + 2026-10-01T12:00:00+00:00 + 2026-10-02T12:00:00+00:00 + + Media Title + + + The video’s description. + + + + + + + diff --git a/Modules/RSParser/Tests/RSParserTests/XML/XMLAttributesTests.swift b/Modules/RSParser/Tests/RSParserTests/XML/XMLAttributesTests.swift index 165c3f102..57626435c 100644 --- a/Modules/RSParser/Tests/RSParserTests/XML/XMLAttributesTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/XML/XMLAttributesTests.swift @@ -116,22 +116,22 @@ import Testing @Test func caseInsensitiveMatchesMixedCaseLocalName() { // RSS's `isPermaLink` vs authors typing `ispermalink`. let a = make(makeAttribute(localName: "isPermaLink", value: "false")) - #expect(a.value(forNameCaseInsensitive: "ispermalink") == "false") - #expect(a.value(forNameCaseInsensitive: "ISPERMALINK") == "false") - #expect(a.value(forNameCaseInsensitive: "IsPermaLink") == "false") + #expect(a.value(forCaseInsensitiveName: "ispermalink") == "false") + #expect(a.value(forCaseInsensitiveName: "ISPERMALINK") == "false") + #expect(a.value(forCaseInsensitiveName: "IsPermaLink") == "false") } @Test func caseInsensitiveMatchesPrefixAndLocal() { let a = make(makeAttribute(prefix: "XML", localName: "Lang", value: "en", uri: "http://www.w3.org/XML/1998/namespace")) - #expect(a.value(forNameCaseInsensitive: "xml:lang") == "en") + #expect(a.value(forCaseInsensitiveName: "xml:lang") == "en") } @Test func caseInsensitiveDoesNotAffectNonLetters() { // Hyphens/digits/punctuation compare byte-for-byte even under case-insensitive. let a = make(makeAttribute(localName: "data-id", value: "42")) - #expect(a.value(forNameCaseInsensitive: "data-id") == "42") - #expect(a.value(forNameCaseInsensitive: "data_id") == nil) + #expect(a.value(forCaseInsensitiveName: "data-id") == "42") + #expect(a.value(forCaseInsensitiveName: "data_id") == nil) } // MARK: - dictionary() diff --git a/Modules/RSTree/Package.swift b/Modules/RSTree/Package.swift index 4f6250c16..e08adcd97 100644 --- a/Modules/RSTree/Package.swift +++ b/Modules/RSTree/Package.swift @@ -3,7 +3,7 @@ import PackageDescription let package = Package( name: "RSTree", - platforms: [.macOS(.v15), .iOS(.v17)], + platforms: [.macOS(.v15), .iOS(.v18)], products: [ .library( name: "RSTree", diff --git a/Modules/RSWeb/.swiftpm/xcode/xcshareddata/xcschemes/RSWebTests.xcscheme b/Modules/RSWeb/.swiftpm/xcode/xcshareddata/xcschemes/RSWebTests.xcscheme index f7f66aa80..528009af1 100644 --- a/Modules/RSWeb/.swiftpm/xcode/xcshareddata/xcschemes/RSWebTests.xcscheme +++ b/Modules/RSWeb/.swiftpm/xcode/xcshareddata/xcschemes/RSWebTests.xcscheme @@ -1,6 +1,6 @@ = resumeDate + // Not >=, which is back-deployed and crashes on iOS 27.2 betas. + Date() > resumeDate } /// canResume with a maximum maxAge. We do this because @@ -28,7 +29,8 @@ public struct CacheControlInfo: Codable, Equatable, Sendable { /// clearly not intentional. public func canResume(maxMaxAge: TimeInterval) -> Bool { let maxAgeToUse = min(maxMaxAge, maxAge) - return Date() >= dateCreated + maxAgeToUse + // Not >=, which is back-deployed and crashes on iOS 27.2 betas. + return Date() > dateCreated + maxAgeToUse } public init(dateCreated: Date, maxAge: TimeInterval) { diff --git a/Modules/RSWeb/Sources/RSWeb/Downloader.swift b/Modules/RSWeb/Sources/RSWeb/Downloader.swift index 7a9a74c7e..93d6985b5 100755 --- a/Modules/RSWeb/Sources/RSWeb/Downloader.swift +++ b/Modules/RSWeb/Sources/RSWeb/Downloader.swift @@ -14,7 +14,8 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi /// Simple downloader, for a one-shot download like an image /// or a web page. For a download-feeds session, see DownloadSession. -/// Caches response for a short time for GET requests. May return cached response. +/// Caches response for a short time for GET requests, unless `cachesResponse` is false. May return cached response. +/// A conditional GET isn’t cached or coalesced with other requests, since its 304 response has no body. @MainActor public final class Downloader { public static let shared = Downloader() private let urlSession: URLSession @@ -42,13 +43,13 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi urlSession.invalidateAndCancel() } - public func download(_ url: URL, userAgentStyle: UserAgentStyle = .feed) async throws -> DownloadResponse { - try await download(URLRequest(url: url), userAgentStyle: userAgentStyle) + public func download(_ url: URL, userAgentStyle: UserAgentStyle = .feed, cachesResponse: Bool = true) async throws -> DownloadResponse { + try await download(URLRequest(url: url), userAgentStyle: userAgentStyle, cachesResponse: cachesResponse) } - public func download(_ urlRequest: URLRequest, userAgentStyle: UserAgentStyle = .feed) async throws -> DownloadResponse { + public func download(_ urlRequest: URLRequest, userAgentStyle: UserAgentStyle = .feed, cachesResponse: Bool = true) async throws -> DownloadResponse { try await withCheckedThrowingContinuation { continuation in - download(urlRequest, userAgentStyle: userAgentStyle) { downloadResponse, error in + download(urlRequest, userAgentStyle: userAgentStyle, cachesResponse: cachesResponse) { downloadResponse, error in if let error { continuation.resume(throwing: error) } else { @@ -63,7 +64,7 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi download(URLRequest(url: url), userAgentStyle: userAgentStyle, callback) } - public func download(_ urlRequest: URLRequest, userAgentStyle: UserAgentStyle = .feed, _ callback: @escaping DownloadCallback) { + public func download(_ urlRequest: URLRequest, userAgentStyle: UserAgentStyle = .feed, cachesResponse: Bool = true, _ callback: @escaping DownloadCallback) { assert(Thread.isMainThread) guard let url = urlRequest.url else { @@ -77,7 +78,8 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi return } - let isCacheableRequest = urlRequest.httpMethod == HTTPMethod.get + let isConditionalRequest = urlRequest.value(forHTTPHeaderField: HTTPRequestHeader.ifNoneMatch) != nil || urlRequest.value(forHTTPHeaderField: HTTPRequestHeader.ifModifiedSince) != nil + let isCacheableRequest = urlRequest.httpMethod == HTTPMethod.get && !isConditionalRequest // Return cached record if available. if isCacheableRequest { @@ -89,7 +91,9 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi } // Add callback. If there is already a download in progress for this URL, return early. - if callbacks[url] == nil { + if isConditionalRequest { + Self.logger.debug("Downloader: downloading \(url) with conditional GET") + } else if callbacks[url] == nil { Self.logger.debug("Downloader: downloading \(url)") callbacks[url] = [(callback, false)] } else { @@ -115,13 +119,17 @@ public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swi let task = urlSession.dataTask(with: urlRequestToUse) { (data, response, error) in // Don’t cache errors — a retry should hit the network. - if isCacheableRequest && error == nil { + if isCacheableRequest && cachesResponse && error == nil { Self.logger.debug("Downloader: caching response for \(url)") self.cache.add(url.absoluteString, data: data, response: response) } Task { @MainActor in - self.callAndReleaseCallbacks(url, data, response, error) + if isConditionalRequest { + callback(DownloadResponse(data: data, response: response, returnedFromCache: false), error) + } else { + self.callAndReleaseCallbacks(url, data, response, error) + } } } task.resume() diff --git a/Modules/RSWeb/Sources/RSWeb/HTTPResponse429.swift b/Modules/RSWeb/Sources/RSWeb/HTTPResponse429.swift index e3006285a..147068d57 100644 --- a/Modules/RSWeb/Sources/RSWeb/HTTPResponse429.swift +++ b/Modules/RSWeb/Sources/RSWeb/HTTPResponse429.swift @@ -20,7 +20,8 @@ struct HTTPResponse429 { dateCreated + TimeInterval(retryAfter) } var canResume: Bool { - Date() >= resumeDate + // Not >=, which is back-deployed and crashes on iOS 27.2 betas. + Date() > resumeDate } init?(url: URL, retryAfter: TimeInterval) { diff --git a/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift b/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift index 81ce508ff..b64628ba8 100644 --- a/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift +++ b/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift @@ -7,7 +7,12 @@ import Foundation import Network -import os +import Synchronization + +extension Notification.Name { + /// Posted on the main thread when `isConnected` or `isConstrained` changes. + public static let networkStatusDidChange = Notification.Name("NetworkStatusDidChange") +} nonisolated public final class NetworkMonitor: Sendable { public static let shared = NetworkMonitor() @@ -18,11 +23,10 @@ nonisolated public final class NetworkMonitor: Sendable { private struct State: Sendable { var isConnected: Bool? var connectionType: NWInterface.InterfaceType? - var isExpensive = false var isConstrained = false } - private let state = OSAllocatedUnfairLock(initialState: State()) + private let state = Mutex(State()) /// `true` until `NWPathMonitor` delivers its first path, so callers attempt /// network work rather than skip it on an answer we don't have yet. @@ -34,11 +38,6 @@ nonisolated public final class NetworkMonitor: Sendable { state.withLock { $0.connectionType } } - /// Is the connection expensive (cellular data with limited plan, for instance) - public var isExpensive: Bool { - state.withLock { $0.isExpensive } - } - /// Is the connection constrained (Low Data Mode enabled, for instance) public var isConstrained: Bool { state.withLock { $0.isConstrained } @@ -68,11 +67,19 @@ nonisolated public final class NetworkMonitor: Sendable { } private func updateStatus(with path: NWPath) { - state.withLock { state in - state.isConnected = path.status == .satisfied + let statusDidChange = state.withLock { state in + let isConnected = path.status == .satisfied + let statusDidChange = isConnected != (state.isConnected ?? true) || path.isConstrained != state.isConstrained + state.isConnected = isConnected state.connectionType = path.availableInterfaces.first?.type - state.isExpensive = path.isExpensive state.isConstrained = path.isConstrained + return statusDidChange + } + guard statusDidChange else { + return + } + Task { @MainActor in + NotificationCenter.default.post(name: .networkStatusDidChange, object: self) } } } diff --git a/Modules/RSWeb/Sources/RSWeb/URL+RSWeb.swift b/Modules/RSWeb/Sources/RSWeb/URL+RSWeb.swift index f90fa8cc4..51e1b07ac 100755 --- a/Modules/RSWeb/Sources/RSWeb/URL+RSWeb.swift +++ b/Modules/RSWeb/Sources/RSWeb/URL+RSWeb.swift @@ -14,7 +14,16 @@ private struct URLConstants { static let schemeMailto = "mailto" static let prefixHTTP = "http://" static let prefixHTTPS = "https://" - static let allowedSchemesForOpening: Set = [schemeHTTP, schemeHTTPS, schemeMailto] + static let schemeNetNewsWire = "netnewswire" + static let schemeFeed = "feed" + static let schemeFeeds = "feeds" +#if os(macOS) + static let schemeMagnet = "magnet" + static let schemeNetNewsWireFeed = "x-netnewswire-feed" + static let allowedSchemesForOpening: Set = [schemeHTTP, schemeHTTPS, schemeMailto, schemeMagnet, schemeNetNewsWire, schemeFeed, schemeFeeds, schemeNetNewsWireFeed] +#else + static let allowedSchemesForOpening: Set = [schemeHTTP, schemeHTTPS, schemeMailto, schemeNetNewsWire, schemeFeed, schemeFeeds] +#endif } public extension URL { @@ -60,7 +69,6 @@ public extension URL { } func preparedForOpeningInBrowser() -> URL? { - // Open http, https, and mailto links only. guard let scheme = scheme?.lowercased(with: localeForLowercasing), URLConstants.allowedSchemesForOpening.contains(scheme) else { return nil diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift index 0a02e8c53..594ef4447 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift @@ -6,7 +6,7 @@ // import Foundation -import os +import Synchronization public final class TestingURLProtocol: URLProtocol { @@ -49,7 +49,7 @@ public final class TestingURLProtocol: URLProtocol { /// Maps a test ID to its state. Requests from a session built outside a /// `currentTestID` scope use `sharedTestID`. - private static let testStates = OSAllocatedUnfairLock<[String: TestState]>(initialState: [:]) + private static let testStates = Mutex<[String: TestState]>([:]) private static let sharedTestID = "shared" diff --git a/Modules/RSWeb/Tests/RSWebTests/URLPreparedForOpeningTests.swift b/Modules/RSWeb/Tests/RSWebTests/URLPreparedForOpeningTests.swift index 1484eb40f..6c6b3806a 100644 --- a/Modules/RSWeb/Tests/RSWebTests/URLPreparedForOpeningTests.swift +++ b/Modules/RSWeb/Tests/RSWebTests/URLPreparedForOpeningTests.swift @@ -17,6 +17,17 @@ struct URLPreparedForOpeningTests { #expect(try url("mailto:me@example.com").preparedForOpeningInBrowser() != nil) } +#if os(macOS) + @Test func allowsMagnetScheme() throws { + #expect(try url("magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn=example").preparedForOpeningInBrowser() != nil) + #expect(try url("Magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a").preparedForOpeningInBrowser() != nil) + } +#else + @Test func blocksMagnetScheme() throws { + #expect(try url("magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn=example").preparedForOpeningInBrowser() == nil) + } +#endif + @Test func blocksOtherSchemes() throws { #expect(try url("smb://server/share").preparedForOpeningInBrowser() == nil) #expect(try url("file:///etc/passwd").preparedForOpeningInBrowser() == nil) diff --git a/Modules/Secrets/Package.swift b/Modules/Secrets/Package.swift index b712e8361..3512db435 100644 --- a/Modules/Secrets/Package.swift +++ b/Modules/Secrets/Package.swift @@ -3,7 +3,7 @@ import PackageDescription let package = Package( name: "Secrets", - platforms: [.macOS(.v15), .iOS(.v17)], + platforms: [.macOS(.v15), .iOS(.v18)], products: [ .library( name: "Secrets", diff --git a/Modules/SyncDatabase/Package.swift b/Modules/SyncDatabase/Package.swift index 330b3ade4..491ca022a 100644 --- a/Modules/SyncDatabase/Package.swift +++ b/Modules/SyncDatabase/Package.swift @@ -3,7 +3,7 @@ import PackageDescription let package = Package( name: "SyncDatabase", - platforms: [.macOS(.v15), .iOS(.v17)], + platforms: [.macOS(.v15), .iOS(.v18)], products: [ .library( name: "SyncDatabase", diff --git a/NetNewsWire.xcodeproj/project.pbxproj b/NetNewsWire.xcodeproj/project.pbxproj index dcd4b2051..cbb5c0af1 100644 --- a/NetNewsWire.xcodeproj/project.pbxproj +++ b/NetNewsWire.xcodeproj/project.pbxproj @@ -52,6 +52,7 @@ 843E2F1D2CF2B8D300ED170F /* RSWeb in Frameworks */ = {isa = PBXBuildFile; productRef = 843E2F1C2CF2B8D300ED170F /* RSWeb */; }; 84719F4C2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/ActivityItemSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84719F4B2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/ActivityItemSourceTests.swift */; }; 84719F4E2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/MultilineUILabelSizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84719F4D2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/MultilineUILabelSizerTests.swift */; }; + 84719F502EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/AppDefaultsMigrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84719F4F2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/AppDefaultsMigrationTests.swift */; }; 848E84CD2DB749440023F3BA /* RSCore in Frameworks */ = {isa = PBXBuildFile; productRef = 848E84CC2DB749440023F3BA /* RSCore */; }; 848E84CE2DB749440023F3BA /* RSCore in Embed Frameworks */ = {isa = PBXBuildFile; productRef = 848E84CC2DB749440023F3BA /* RSCore */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; 848E84D02DB749440023F3BA /* RSCoreResources in Frameworks */ = {isa = PBXBuildFile; productRef = 848E84CF2DB749440023F3BA /* RSCoreResources */; }; @@ -77,6 +78,10 @@ 849182DD2FD32B1B005C3035 /* Sepia.nnwtheme in Resources */ = {isa = PBXBuildFile; fileRef = 849182BB2FD32B1B005C3015 /* Sepia.nnwtheme */; }; 849182DD2FD32B1B005C3036 /* Tiqoe Dark.nnwtheme in Resources */ = {isa = PBXBuildFile; fileRef = 849182BB2FD32B1B005C3016 /* Tiqoe Dark.nnwtheme */; }; 849182DD2FD32B1B005C3037 /* Verdana Revival.nnwtheme in Resources */ = {isa = PBXBuildFile; fileRef = 849182BB2FD32B1B005C3017 /* Verdana Revival.nnwtheme */; }; + 84CCB45330A40989004B73CC /* Plum.nnwtheme in Resources */ = {isa = PBXBuildFile; fileRef = 84CCB45230A40989004B73CC /* Plum.nnwtheme */; }; + 84CCB45430A40989004B73CC /* Gray.nnwtheme in Resources */ = {isa = PBXBuildFile; fileRef = 84CCB45130A40989004B73CC /* Gray.nnwtheme */; }; + 84CCB45530A40989004B73CC /* Plum.nnwtheme in Resources */ = {isa = PBXBuildFile; fileRef = 84CCB45230A40989004B73CC /* Plum.nnwtheme */; }; + 84CCB45630A40989004B73CC /* Gray.nnwtheme in Resources */ = {isa = PBXBuildFile; fileRef = 84CCB45130A40989004B73CC /* Gray.nnwtheme */; }; 84EE3F122DB8A088009D3A8D /* RSTree in Frameworks */ = {isa = PBXBuildFile; productRef = 84EE3F112DB8A088009D3A8D /* RSTree */; }; 84EE3F132DB8A088009D3A8D /* RSTree in Embed Frameworks */ = {isa = PBXBuildFile; productRef = 84EE3F112DB8A088009D3A8D /* RSTree */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; 84EE3F152DB8A0A0009D3A8D /* RSTree in Frameworks */ = {isa = PBXBuildFile; productRef = 84EE3F142DB8A0A0009D3A8D /* RSTree */; }; @@ -287,6 +292,7 @@ 845B14A51FC2299E0013CF92 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 84719F4B2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/ActivityItemSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/NetNewsWire-iOSTests/ActivityItemSourceTests.swift"; sourceTree = SOURCE_ROOT; }; 84719F4D2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/MultilineUILabelSizerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/NetNewsWire-iOSTests/MultilineUILabelSizerTests.swift"; sourceTree = SOURCE_ROOT; }; + 84719F4F2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/AppDefaultsMigrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/NetNewsWire-iOSTests/AppDefaultsMigrationTests.swift"; sourceTree = SOURCE_ROOT; }; 848CEF1E2DB74B56002B35B5 /* NetNewsWire-iOS.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = "NetNewsWire-iOS.xctestplan"; sourceTree = ""; }; 848E84C92DB743FF0023F3BA /* NetNewsWire-CI.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = "NetNewsWire-CI.xctestplan"; sourceTree = ""; }; 848E84CA2DB743FF0023F3BA /* NetNewsWire.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = NetNewsWire.xctestplan; sourceTree = ""; }; @@ -300,6 +306,8 @@ 849182BB2FD32B1B005C3017 /* Verdana Revival.nnwtheme */ = {isa = PBXFileReference; lastKnownFileType = folder; path = "Verdana Revival.nnwtheme"; sourceTree = ""; }; 849C64601ED37A5D003D8FC0 /* NetNewsWire.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = NetNewsWire.app; sourceTree = BUILT_PRODUCTS_DIR; }; 849C64711ED37A5D003D8FC0 /* NetNewsWireTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = NetNewsWireTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 84CCB45130A40989004B73CC /* Gray.nnwtheme */ = {isa = PBXFileReference; lastKnownFileType = wrapper; path = Gray.nnwtheme; sourceTree = ""; }; + 84CCB45230A40989004B73CC /* Plum.nnwtheme */ = {isa = PBXFileReference; lastKnownFileType = wrapper; path = Plum.nnwtheme; sourceTree = ""; }; 84D2200922B0BC4B0019E085 /* CONTRIBUTING.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = CONTRIBUTING.md; sourceTree = ""; }; /* End PBXFileReference section */ @@ -331,7 +339,6 @@ isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( /Localized/ShareExtension/ShareViewController.xib, - AppDefaults.swift, ShareExtension/icon.icns, ShareExtension/ShareViewController.swift, ); @@ -348,6 +355,7 @@ isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( "NetNewsWire-iOSTests/ActivityItemSourceTests.swift", + "NetNewsWire-iOSTests/AppDefaultsMigrationTests.swift", "NetNewsWire-iOSTests/MultilineUILabelSizerTests.swift", ); target = 849C64701ED37A5D003D8FC0 /* NetNewsWireTests */; @@ -375,7 +383,6 @@ 84A6D0402D1B4EC500F23315 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( - AppDefaults.swift, Resources/Assets.xcassets, ShareExtension/ShareFolderPickerAccountCell.xib, ShareExtension/ShareFolderPickerCell.swift, @@ -413,7 +420,6 @@ 84D35E0C2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( - ArticleSpecifier.swift, Assets.swift, "Extensions/Node+Extensions.swift", ShareExtension/ExtensionContainers.swift, @@ -422,7 +428,6 @@ ShareExtension/ExtensionFeedAddRequestFile.swift, ShareExtension/SafariExt.js, ShareExtension/ShareDefaultContainer.swift, - UserInfoKey.swift, ); target = 513C5CE5232571C2003D4054 /* NetNewsWire iOS Share Extension */; }; @@ -439,14 +444,12 @@ 84D35E0F2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( - "Article Rendering/ArticleTextSize.swift", ShareExtension/ExtensionContainers.swift, ShareExtension/ExtensionContainersFile.swift, ShareExtension/ExtensionFeedAddRequest.swift, ShareExtension/ExtensionFeedAddRequestFile.swift, ShareExtension/SafariExt.js, ShareExtension/ShareDefaultContainer.swift, - Timer/RefreshInterval.swift, ); target = 510C415B24E5CDE3008226FD /* NetNewsWire Share Extension */; }; @@ -571,6 +574,7 @@ children = ( 84719F4B2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/ActivityItemSourceTests.swift */, 84719F4D2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/MultilineUILabelSizerTests.swift */, + 84719F4F2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/AppDefaultsMigrationTests.swift */, ); name = "Recovered References"; sourceTree = ""; @@ -580,8 +584,10 @@ children = ( 849182BB2FD32B1B005C3010 /* Appanoose.nnwtheme */, 849182BB2FD32B1B005C3011 /* Biblioteca.nnwtheme */, + 84CCB45130A40989004B73CC /* Gray.nnwtheme */, 849182BB2FD32B1B005C3012 /* Hyperlegible.nnwtheme */, 849182BB2FD32B1B005C3013 /* NewsFax.nnwtheme */, + 84CCB45230A40989004B73CC /* Plum.nnwtheme */, 849182BB2FD32B1B005C3014 /* Promenade.nnwtheme */, 849182BB2FD32B1B005C3015 /* Sepia.nnwtheme */, 849182BB2FD32B1B005C3016 /* Tiqoe Dark.nnwtheme */, @@ -866,7 +872,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 1240; - LastUpgradeCheck = 2710; + LastUpgradeCheck = 2720; ORGANIZATIONNAME = "Ranchero Software"; TargetAttributes = { 176813F22564BB2C00D98635 = { @@ -996,6 +1002,8 @@ 849182DD2FD32B1B005C3032 /* Hyperlegible.nnwtheme in Resources */, 849182DD2FD32B1B005C3033 /* NewsFax.nnwtheme in Resources */, 849182DD2FD32B1B005C3034 /* Promenade.nnwtheme in Resources */, + 84CCB45330A40989004B73CC /* Plum.nnwtheme in Resources */, + 84CCB45430A40989004B73CC /* Gray.nnwtheme in Resources */, 849182DD2FD32B1B005C3035 /* Sepia.nnwtheme in Resources */, 849182DD2FD32B1B005C3036 /* Tiqoe Dark.nnwtheme in Resources */, 849182DD2FD32B1B005C3037 /* Verdana Revival.nnwtheme in Resources */, @@ -1014,6 +1022,8 @@ 849182CC2FD32B1B005C3025 /* Sepia.nnwtheme in Resources */, 849182CC2FD32B1B005C3026 /* Tiqoe Dark.nnwtheme in Resources */, 849182CC2FD32B1B005C3027 /* Verdana Revival.nnwtheme in Resources */, + 84CCB45530A40989004B73CC /* Plum.nnwtheme in Resources */, + 84CCB45630A40989004B73CC /* Gray.nnwtheme in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1167,6 +1177,7 @@ files = ( 84719F4C2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/ActivityItemSourceTests.swift in Sources */, 84719F4E2EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/MultilineUILabelSizerTests.swift in Sources */, + 84719F502EE01A1100EEF332 /* Tests/NetNewsWire-iOSTests/AppDefaultsMigrationTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/NetNewsWire.xcodeproj/xcshareddata/xcschemes/NetNewsWire iOS Share Extension.xcscheme b/NetNewsWire.xcodeproj/xcshareddata/xcschemes/NetNewsWire iOS Share Extension.xcscheme index a8fa10bd4..5cd04f6fa 100644 --- a/NetNewsWire.xcodeproj/xcshareddata/xcschemes/NetNewsWire iOS Share Extension.xcscheme +++ b/NetNewsWire.xcodeproj/xcshareddata/xcschemes/NetNewsWire iOS Share Extension.xcscheme @@ -1,6 +1,6 @@ .systemMessage { - color: var(--system-message-color); -} - -.feedIcon { - border-radius: 4px; -} - -.attribution { - line-height: 1.2; - margin-left: 4px; - margin-right: 4px; - display: inline-block; - vertical-align: middle; - text-align: left; - flex: 20 1 auto; - color: var(--attribution-color); -} - -.feedLink { - color: var(--attribution-color); -} - -.byline { - color: var(--attribution-color); - font-size: 66%; -} - -body .byline a:link, .byline a:visited { - color: var(--attribution-color); -} - -.rightAlign { - text-align: end; -} - -.leftAlign { - text-align: start; -} - -.articleTitle { - margin-top: 16px; - font-size: 1.2em; - font-weight: bold; - color: var(--article-title-color); - text-align: center; -} - -.articleTitle a:link, .articleTitle a:visited { - color: var(--article-title-color); -} - -.articleDateline { - color: var(--article-date-color); -} - -.articleDateline a:link, .articleDateline a:visited { - color: var(--article-date-color); -} - -.articleDatelineTitle a:link, .articleDatelineTitle a:visited { - color: var(--article-title-color); -} - -.externalLink { - font-style: italic; - width: 100%; -} - -.singleLine { - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - -body .externalLink a:link, .externalLink a:visited { - color: var(--article-title-color); -} - -.articleBody { - margin-top: 10px; - line-height: 1.6em; -} - -h1 { - line-height: 1.15em; - font-weight: bold; - padding-bottom: 0; - margin-bottom: 5px; -} - -h3 { - font-weight: bold; - margin-bottom: 3px; -} - -pre { - max-width: 100%; - margin: 0; - overflow: auto; - overflow-y: hidden; - word-wrap: normal; - word-break: normal; -} - -pre { - line-height: 1.4286em; -} - -code, pre { - font-family: "SF Mono", Menlo, "Courier New", Courier, monospace; - font-size: 1em; - -webkit-hyphens: none; -} - -pre code { - letter-spacing: -.027em; - font-size: 0.9375em; -} - -.nnw-overflow { - overflow-x: auto; -} - -.avatar { - vertical-align: middle; - border-radius: 4px; - height: 2em; - width: 2em; - min-width: 2em; -} - -/* - Instead of the last-child bits, border-collapse: collapse - could have been used. However, then the inter-cell borders - overlap the table border, which looks bad. - */ -.nnw-overflow table { - margin-bottom: 1px; - border-spacing: 0; - border: 1px solid var(--secondary-accent-color); - font-size: inherit; -} - -.nnw-overflow table table { - margin-bottom: 0; - border: none; -} - -.nnw-overflow td, .nnw-overflow th { - -webkit-hyphens: none; - word-break: normal; - border: 1px solid var(--table-cell-border-color); - border-top: none; - border-left: none; - padding: 5px; -} - -.nnw-overflow tr :matches(td, th):last-child { - border-right: none; -} - -.nnw-overflow :matches(thead, tbody, tfoot):last-child > tr:last-child :matches(td, th) { - border-bottom: none; -} - -.nnw-overflow td pre { - border: none; - padding: 0; -} - -.nnw-overflow table[border="0"] { - border-width: 0; -} - -img, figure, video, div, object { - max-width: 100%; - height: auto !important; - margin: 0 auto; -} - -iframe { - max-width: 100%; - margin: 0 auto; -} - -iframe.nnw-constrained { - max-height: 50vw; -} - -figure { - margin-bottom: 1em; - margin-top: 1em; -} - -figcaption { - font-size: 14px; - line-height: 1.3em; -} - -sup { - vertical-align: top; - position: relative; - bottom: 0.2rem; -} - -sub { - vertical-align: bottom; - position: relative; - top: 0.2rem; -} - -hr { - border: 1.5px solid var(--table-cell-border-color); -} - -.iframeWrap { - position: relative; - display: block; - padding-top: 56.25%; -} - -.iframeWrap iframe { - position: absolute; - top: 0; - left: 0; - height: 100% !important; - width: 100% !important; -} - -blockquote { - margin-inline-start: 0; - margin-inline-end: 0; - padding-inline-start: 15px; - border-inline-start: 3px solid var(--block-quote-border-color); -} - -/* Feed Specific */ - -.feedbin--article-wrap { - border-top: 1px solid var(--footer-table-border-color); -} - -/* Twitter */ - -.twitterAvatar { - vertical-align: middle; - border-radius: 4px; - height: 1.7em; - width: 1.7em; -} - -.twitterUsername { - line-height: 1.2; - margin-left: 4px; - display: inline-block; - vertical-align: middle; -} - -.twitterScreenName { - font-size: 66%; -} - -.twitterTimestamp { - font-size: 66%; -} - -/* Newsfoot theme for light mode (default) */ -.newsfoot-footnote-popover { - background: #ccc; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5), 0 3px 6px rgba(0, 0, 0, 0.25); - color: black; - padding: 1px; -} - -.newsfoot-footnote-popover-arrow { - background: #fafafa; - border: 1px solid #ccc; -} - -.newsfoot-footnote-popover-inner { - background: #fafafa; -} - -body a.footnote, -body a.footnote:visited, -.newsfoot-footnote-popover + a.footnote:hover { - background: #aaa; - color: white; - transition: background-color 200ms ease-out; -} - -a.footnote:hover, -.newsfoot-footnote-popover + a.footnote { - background: #666; - transition: background-color 200ms ease-out; -} - -/* Newsfoot theme for dark mode */ -@media screen and (prefers-color-scheme: dark) { - .newsfoot-footnote-popover { - background: #444; - color: rgb(224, 224, 224); - } - - .newsfoot-footnote-popover-arrow { - background: #242424; - border: 1px solid #444; - } - - .newsfoot-footnote-popover-inner { - background: #242424; - } - - body a.footnote, - body a.footnote:visited, - .newsfoot-footnote-popover + a.footnote:hover { - background: #aaa; - color: white; - transition: background-color 200ms ease-out; - } - - a.footnote:hover, - .newsfoot-footnote-popover + a.footnote { - background: #666; - transition: background-color 200ms ease-out; - } - -} - -/* iOS Specific */ -@supports (-webkit-touch-callout: none) { - - body { - margin-top: 3px; - margin-bottom: 20px; - margin-left: 20px; - margin-right: 20px; - - word-break: break-word; - -webkit-hyphens: auto; - -webkit-text-size-adjust: none; - } - - :root { - color-scheme: light dark; - font: -apple-system-body; - /* The font-size is replaced at runtime by the dynamic type size */ - font-size: [[font-size]]px; - --primary-accent-color: #086AEE; - --secondary-accent-color: #086AEE; - --block-quote-border-color: rgba(8, 106, 238, 0.50); - --secondary-accent-color: #086AEE; - } - - @media(prefers-color-scheme: dark) { - :root { - --primary-accent-color: #2D80F1; - --secondary-accent-color: #5E9EF4; - --block-quote-border-color: rgba(94, 158, 244, 0.50); - --footer-table-border-color: rgba(255, 255, 255, 0.2); - } - } - - body a, body a:visited, body a * { - color: var(--secondary-accent-color); - } - - .fontSize { - font: -apple-system-body; - font-size: [[font-size]]px; - } - - pre { - border: 1px solid var(--secondary-accent-color); - padding: 5px; - } - - .nnw-overflow table { - border: 1px solid var(--secondary-accent-color); - } - -} - -/* macOS Specific */ -@supports not (-webkit-touch-callout: none) { - - body { - margin-top: 20px; - margin-bottom: 20px; - margin-left: auto; - margin-right: auto; - padding-left: 48px; - padding-right: 48px; - font-family: -apple-system; - } - - .smallText { - font-size: 14px; - } - - .mediumText { - font-size: 16px; - } - - .largeText { - font-size: 18px; - } - - .xlargeText { - font-size: 20px; - } - - .xxlargeText { - font-size: 22px; - } - - :root { - color-scheme: light dark; - --accent-color: rgba(8, 106, 238, 1); - --block-quote-border-color: rgba(8, 106, 238, .50); - } - - @media(prefers-color-scheme: dark) { - :root { - --accent-color: rgba(94, 158, 244, 1); - --block-quote-border-color: rgba(94, 158, 244, .50); - } - } - - body a, body a:visited, body a * { - color: var(--accent-color); - } - - pre { - border: 1px solid var(--accent-color); - padding: 10px; - } - - .nnw-overflow table { - border: 1px solid var(--accent-color); - } - -} diff --git a/Resources/Themes/Biblioteca.nnwtheme/Info.plist b/Resources/Themes/Biblioteca.nnwtheme/Info.plist deleted file mode 100644 index 6c9fada3a..000000000 --- a/Resources/Themes/Biblioteca.nnwtheme/Info.plist +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Name - Biblioteca - ThemeIdentifier - com.netnewswire.themes.biblioteca - CreatorHomePage - https://martingonzalez.net/ - CreatorName - Martín González Gómez - Version - 1 - - diff --git a/Resources/Themes/Biblioteca.nnwtheme/stylesheet.css b/Resources/Themes/Biblioteca.nnwtheme/stylesheet.css deleted file mode 100644 index 9e64d71a6..000000000 --- a/Resources/Themes/Biblioteca.nnwtheme/stylesheet.css +++ /dev/null @@ -1,496 +0,0 @@ -/* Shared iOS and macOS CSS rules. Platform specific rules are at the bottom of this file. */ -:root { - --header-table-border-color: rgba(0, 0, 0, 0.1); - --body-code-color: #fff; - --system-message-color: #111; - --feedlink-color: #777; - --article-title-color: #111; - --article-secondary-color: rgba(0, 0, 0, 0.5); - --table-cell-border-color: #dedede; - --table-header-border-color: #999; - --secondary-accent-color: #1145a5; - --block-quote-border-color: rgba(0, 0, 0, 0.3); - --font-serif: ui-serif, serif; - --font-sans: ui-sans-serif, sans-serif; - --font-mono: ui-monospace, monospace; - --background-color: #fff; - --font-color: #111; - --code-background-border: transparent; - --code-background: #403f3f; - --font-size-title: 0.9em; - --font-size-secondary: 0.8em; - --body-line-height: 1.475; -} -@media (prefers-color-scheme: dark) { - :root { - --header-table-border-color: rgba(255, 255, 255, 0.1); - --font-color: #ededed; - --background-color: #1E1E1E; - --header-color: rgba(255, 255, 255, 0.5); - --article-title-color: #fff; - --article-secondary-color: rgba(255, 255, 255, 0.65); - --secondary-accent-color: #7aa1e8; - --feedlink-color: rgba(255, 255, 255, 0.65); - --body-code-color: #f5f5f5; - --block-quote-border-color: rgba(255, 255, 255, 0.2); - --table-cell-border-color: rgba(255,255,255,0.1); - --table-header-border-color: rgba(255,255,255,0.3); - --code-background-border: #dedede20; - --code-background: #424141; - --system-message-color: #777; - } -} -@media (min-width: 400px) { - :root { - --font-size-title: 1em; - --font-size-secondary: 0.9em; - } -} -@media (min-width: 740px) { - :root { - --font-size-title: 1.125em; - --body-line-height: 1.6; - } -} - -body { - margin-left: auto; - margin-right: auto; - padding-left: 20px; - padding-right: 20px; - word-wrap: break-word; - max-width: 42em; - color: var(--font-color); - background-color: var(--background-color); -} -a, -a:visited, -a * { - color: var(--secondary-accent-color); -} -a { - text-decoration: underline; - text-decoration-thickness: 1px; - text-underline-offset: 2px; -} -a:hover { - text-decoration: none; -} - -h1 { - line-height: 1.2; - font-weight: 700; -} -h2, -h3, -h4, -h5, -h6 { - line-height: 1.2; - font-family: var(--font-sans); - margin-top: 1.5em; - margin-bottom: 0.25em; -} -h2 + p, -h3 + p, -h4 + p, -h5 + p, -h6 + p { - margin-top: 0; -} - -pre { - max-width: 100%; - margin: 0; - font-family: var(--font-mono); - background-color: var(--code-background); - color: var(--body-code-color); - font-size: 0.8rem; - border: 1px solid var(--code-background-border); - border-radius: 8px; - padding: 8px 12px; - overflow: auto; - overflow-y: hidden; - word-wrap: normal; - word-break: normal; - line-height: 1.4286em; - -webkit-hyphens: none; -} -code { - font-family: var(--font-mono); - font-size: 85%; -} -/* reset size of code in fences */ -pre code { - font-size: 100%; -} - -code a, -pre a { - color: var(--body-code-color); -} -img, -figure, -video, -object { - max-width: 100%; - height: auto !important; - margin: 0 auto; -} -figure, -img { - margin-top: 1.25em; - margin-bottom: 1.25em; -} -figure img { - margin-top: 0; - margin-bottom: 0; -} -figcaption { - color: var(--article-secondary-color); - margin-top: 8px; - font-family: var(--font-sans); - font-size: 14px; - line-height: 1.3em; -} -ul li:not(:last-child) { - margin-bottom: 0.5em; -} -sup { - vertical-align: top; - position: relative; - bottom: 0.2rem; -} -sub { - vertical-align: bottom; - position: relative; - top: 0.2rem; -} -hr { - border: 1.5px solid var(--table-cell-border-color); -} -blockquote { - margin-inline-start: 0; - margin-inline-end: 0; - padding-inline-start: 15px; - border-inline-start: 3px solid var(--block-quote-border-color); -} -form { - font-family: var(--font-sans); -} -iframe { - max-width: 100%; - margin: 0 auto; -} -iframe.nnw-constrained { - max-height: 50vw; -} -.iframeWrap { - position: relative; - display: block; - padding-top: 56.25%; -} -.iframeWrap iframe { - position: absolute; - top: 0; - left: 0; - height: 100% !important; - width: 100% !important; -} -table { - font-size: 0.9em; - border-collapse: collapse; - width: 100%; -} -table thead th { - border-bottom: 1px solid var(--table-header-border-color); - padding-bottom: 8px; - text-align: left; - padding-left: 8px; - padding-right: 8px; -} -table tbody td { - border-bottom: 1px solid var(--table-cell-border-color); - padding: 8px; -} -table tbody tr:last-child td { - border-bottom: none; -} -table thead th:first-child, -table tr td:first-child { - padding-left: 0; -} -table thead th:last-child, -table tr td:last-child { - padding-right: 0; -} -/* avoid horizontal overflow on small screens */ -@media (max-width: 600px) { - table { - display: block; - overflow-x: auto; - -webkit-overflow-scrolling: touch; - } -} - -/* Article header */ -.header-container { - font-size: var(--font-size-secondary); - display: flex; - align-items: center; - justify-content: flex-start; - font-family: var(--font-sans); - font-style: italic; - padding-top: 5px; -} -@media (min-width: 740px) { - .header-container { - padding-top: 0; - padding-bottom: 5px; - border-bottom: 1px solid var(--header-table-border-color); - justify-content: center; - } -} -.header-container img { - width: 20px; - height: 20px; - margin-right: 8px; - margin-top: 8px; - margin-bottom: 8px; -} -@media (min-width: 740px) { - .header-container img { - width: 32px; - height: 32px; - margin-right: 10px; - margin-top: 10px; - margin-bottom: 10px; - } -} -.header-container a, -.header-container a:link, -.header-container a:visited { - text-decoration: none; - color: var(--feedlink-color); -} -.article-title { - font-family: var(--font-serif); - -webkit-transform: translate3d(0, 0, 0); - font-size: var(--font-size-title); - text-wrap: balance; -} -.article-title h1 { - margin-top: 5px; - margin-bottom: 10px; -} -@media (min-width: 740px) { - .article-title h1 { - margin-top: 20px; - } -} -.article-title a:link, -.article-title a:visited { - text-decoration: none; - color: var(--article-title-color); -} -.articleDateline { - color: var(--article-secondary-color); - font-family: var(--font-sans); - font-size: var(--font-size-secondary); - align-items: baseline; - display: flex; - flex-wrap: wrap; -} -@media (min-width: 740px) { - .header-container { - font-size: 0.9em; - } -} -.articleDateline .byline { - font-weight: 600; - display: inline-block; - margin-right: 8px; -} -.articleDateline .byline:empty { - display: none; -} -.articleDateline .byline:not(:empty)::before { - content: "By " -} -.articleDateline a:link, -.articleDateline a:visited { - color: var(--article-secondary-color); - text-decoration: none; -} - -/* Links */ -.external-link { - margin-bottom: 5px; - font-style: italic; - width: 100%; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} -.external-link a:link, -.external-link a:visited { - text-decoration: none; -} - -/* Running copy */ -.article-body { - font-family: var(--font-serif); - line-height: var(--body-line-height); - margin-top: 1em; - margin-bottom: 2em; -} -@media (min-width: 740px) { - .article-body { - margin-bottom: 4em; - } -} -.nnw-overflow { - overflow-x: auto; -} -.systemMessage { - color: var(--system-message-color); - position: absolute; - top: 45%; - left: 50%; - transform: translateX(-55%) translateY(-50%); - -webkit-user-select: none; - cursor: default; -} - -/* Footnotes */ -.newsfoot-footnote-popover { - background: #ccc; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5), 0 3px 6px rgba(0, 0, 0, 0.25); - color: var(--font-color); - padding: 1px; -} -.newsfoot-footnote-popover-arrow { - background: #fbf0d9; - border: 1px solid #ccc; -} -.newsfoot-footnote-popover-inner { - background: #fbf0d9; -} -body a.footnote, -body a.footnote:visited, -.newsfoot-footnote-popover + a.footnote:hover { - font-family: var(--font-sans); - color: var(--font-color); - font-weight: 700; - padding: 0; - transition: background-color 200ms ease-out; -} - -@media (prefers-color-scheme: dark) { - .newsfoot-footnote-popover { - background: #444; - color: #ededed; - } - .newsfoot-footnote-popover-arrow { - background: #2a2a2a; - border: 1px solid #444; - } - .newsfoot-footnote-popover-inner { - background: #2a2a2a; - } -} - -/* Feed Specific */ -.feedbin--article-wrap { - border-top: 1px solid var(--header-table-border-color); -} -.captioned-image-container figure a { - position: relative; -} -/* Substack images */ -.image-link .restack-image, -[data-sanitized-class="captioned-image-container"] [data-sanitized-class="restack-image"] { - display: none; -} -.image-link .image-link-expand, -[data-sanitized-class="captioned-image-container"] [data-sanitized-class="image-link-expand"] { - display: none -} -.footnote, -[data-sanitized-class="footnote"] { - font-size: 90%; - display: flex; - align-items: baseline; - border-top: 1px solid var(--table-cell-border-color); - gap: 20px; -} -/* Wordpress block editor */ -.wp-block-image > .aligncenter { - margin-left: auto; - margin-right: auto; - display: table; -} -/* Twitter */ -.twitterAvatar { - vertical-align: middle; - border-radius: 4px; - height: 1.7em; - width: 1.7em; -} -.twitterUsername { - line-height: 1.2; - margin-left: 4px; - display: inline-block; - vertical-align: middle; -} -.twitterScreenName { - font-size: 66%; -} -.twitterTimestamp { - font-size: 66%; -} -/* force datawrapper to have white background in dark mode */ -@media (prefers-color-scheme: dark) { - #iframe-datawrapper, - [data-sanitized-id="iframe-datawrapper"] { - background-color: white; - } -} - - -/* iOS Specific */ -@supports (-webkit-touch-callout: none) { - :root { - color-scheme: light dark; - --background-color: Canvas; - } - body { - word-break: break-word; - -webkit-hyphens: none; - -webkit-text-size-adjust: none; - font-size: [[font-size]]px; - } -} - -/* macOS Specific */ -@supports not (-webkit-touch-callout: none) { - .smallText { - font-size: 16px; - } - - .mediumText { - font-size: 18px; - } - - .largeText { - font-size: 20px; - } - - .xlargeText { - font-size: 22px; - } - - .xxlargeText { - font-size: 24px; - } -} diff --git a/Resources/Themes/Hyperlegible.nnwtheme/Info.plist b/Resources/Themes/Hyperlegible.nnwtheme/Info.plist deleted file mode 100644 index f1c81c132..000000000 --- a/Resources/Themes/Hyperlegible.nnwtheme/Info.plist +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Name - Hyperlegible - ThemeIdentifier - com.netnewswire.themes.hyperlegible - CreatorHomePage - http://netnewswire.com/ - CreatorName - Ranchero Software - Version - 1 - - diff --git a/Resources/Themes/Hyperlegible.nnwtheme/stylesheet.css b/Resources/Themes/Hyperlegible.nnwtheme/stylesheet.css deleted file mode 100644 index 97758b6dd..000000000 --- a/Resources/Themes/Hyperlegible.nnwtheme/stylesheet.css +++ /dev/null @@ -1,513 +0,0 @@ -/* Shared iOS and macOS CSS rules. Platform specific rules are at the bottom of this file. */ - -@font-face { -font-family: 'Atkinson Hyperlegible'; -src: url(data:application/x-font-woff;charset=utf-8;base64,d09GRgABAAAAAHesABIAAAAA3+gAAQAGAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAB3kAAAABwAAAAck3JOuEdERUYAAGA0AAAAbAAAAIwU4BK+R1BPUwAAY8AAABPNAAAoRrC7U8FHU1VCAABgoAAAAx4AAAYc4NkJqk9TLzIAAAIQAAAAUAAAAGCBnCDDY21hcAAABSAAAALGAAAD9gczDpZjdnQgAAAPfAAAAD8AAABsFcEKtGZwZ20AAAfoAAAG7QAADgxiLv99Z2FzcAAAYCwAAAAIAAAACAAAABBnbHlmAAASnAAAReIAAIQ4XYakcGhlYWQAAAGUAAAANgAAADYdIfmzaGhlYQAAAcwAAAAhAAAAJAiJBDlobXR4AAACYAAAAr0AAAXMyCo9sWxvY2EAAA+8AAAC3wAAAuiJXKjgbWF4cAAAAfAAAAAgAAAAIALNAdZuYW1lAABYgAAAA28AAAdr3bIeinBvc3QAAFvwAAAEPAAAB0QQWsLHcHJlcAAADtgAAACiAAAAvVqx3zsAAQAAAAEBiTHL1OxfDzz1AB8D6AAAAADcbc81AAAAANyw5ZL/xv8GBQoDeAAAAAgAAgAAAAAAAHicY2BkYGDe9u8eAwOrwf9j/7azcjEARZABYzEAov4GygAAAAABAAABcwBYAAcAVAAEAAIAKgBXAI0AAACVANAAAgABeJxjYGESYZzAwMrAwNTFtJuBgaEHQjPeZzBkZGJAAg0MDO8ZGBS8YXw/fz9XhgMMvKqnmLf9u8fAwLyNUUkBSIHkGD8wzQFSCgwcAKedDvR4nJ2US0iUURiG33P+JBHJCBEvXTUHTS2dHKeLpeU4aSl2MckKKogCowu5alFuW4hGqxZhtWwRYUHUshYSkd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) format('woff'); -} - -body { - margin-left: auto; - margin-right: auto; - - word-wrap: break-word; - max-width: 44em; -} - -a { - text-decoration: none; -} - -a:hover { - text-decoration: underline; -} - -.feedlink { - font-weight: bold; -} - -.headerTable { - width: 100%; - height: 68px; -} - -.systemMessage { - position: absolute; - top: 45%; - left: 50%; - transform: translateX(-55%) translateY(-50%); - -webkit-user-select: none; - cursor: default; -} - -:root { - --header-table-border-color: rgba(0, 0, 0, 0.1); - --header-color: rgba(8, 106, 238, 1); - --body-code-color: #666; - --system-message-color: #cbcbcb; - --feedlink-color: rgba(255, 0, 0, 0.6); - --article-title-color: #333; - --article-date-color: rgba(0, 0, 0, 0.5); - --table-cell-border-color: lightgray; -} - -@media(prefers-color-scheme: dark) { - :root { - --header-color: rgba(94, 158, 244, 1); - --body-code-color: #b2b2b2; - --system-message-color: #5f5f5f; - --feedlink-color: rgba(94, 158, 244, 1); - --article-title-color: #e0e0e0; - --article-date-color: rgba(255, 255, 255, 0.8); - --table-cell-border-color: dimgray; - } -} - -body .headerTable { - border-bottom: 1px solid var(--header-table-border-color); - color: var(--header-color); -} - -body .header { - color: var(--header-color); -} - -body .header a:link, .header a:visited { - color: var(--header-color); -} - -body code, body pre { - color: var(--body-code-color); -} - -body > .systemMessage { - color: var(--system-message-color); -} - -.feedlink a:link, .feedlink a:visited { - color: var(--feedlink-color); -} - -.avatar img { - border-radius: 4px; -} - -.feedIcon { - border-radius: 4px; -} - -.rightAlign { - text-align: end; -} - -.leftAlign { - text-align: start; -} - -.articleTitle a:link, .articleTitle a:visited { - color: var(--article-title-color); - margin-top: 26px; -} - -.articleDateline { - margin-bottom: 5px; - font-weight: bold; -} - -.articleDateline a:link, .articleDateline a:visited { - color: var(--article-date-color); -} - -.articleDatelineTitle { - margin-bottom: 5px; - font-weight: bold; -} - -.articleDatelineTitle a:link, .articleDatelineTitle a:visited { - color: var(--article-title-color); -} - -.externalLink { - margin-bottom: 5px; - font-style: italic; - width: 100%; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - -.articleBody { - margin-top: 20px; - line-height: 1.6em; -} - -h1 { - line-height: 1.15em; - font-weight: bold; - padding-bottom: 0; - margin-bottom: 5px; -} - -pre { - max-width: 100%; - margin: 0; - overflow: auto; - overflow-y: hidden; - word-wrap: normal; - word-break: normal; -} - -pre { - line-height: 1.4286em; -} - -code, pre { - font-family: "SF Mono", Menlo, "Courier New", Courier, monospace; - font-size: 1em; - -webkit-hyphens: none; -} - -pre code { - letter-spacing: -.027em; - font-size: 0.9375em; -} - -.nnw-overflow { - overflow-x: auto; -} - -/* - Instead of the last-child bits, border-collapse: collapse - could have been used. However, then the inter-cell borders - overlap the table border, which looks bad. - */ -.nnw-overflow table { - margin-bottom: 1px; - border-spacing: 0; - border: 1px solid var(--secondary-accent-color); - font-size: inherit; -} - -.nnw-overflow table table { - margin-bottom: 0; - border: none; -} - -.nnw-overflow td, .nnw-overflow th { - -webkit-hyphens: none; - word-break: normal; - border: 1px solid var(--table-cell-border-color); - border-top: none; - border-left: none; - padding: 5px; -} - -.nnw-overflow tr :matches(td, th):last-child { - border-right: none; -} - -.nnw-overflow :matches(thead, tbody, tfoot):last-child > tr:last-child :matches(td, th) { - border-bottom: none; -} - -.nnw-overflow td pre { - border: none; - padding: 0; -} - -.nnw-overflow table[border="0"] { - border-width: 0; -} - -img, figure, video, div, object { - max-width: 100%; - height: auto !important; - margin: 0 auto; -} - -iframe { - max-width: 100%; - margin: 0 auto; -} - -iframe.nnw-constrained { - max-height: 50vw; -} - -figure { - margin-bottom: 1em; - margin-top: 1em; -} - -figcaption { - font-size: 14px; - line-height: 1.3em; -} - -sup { - vertical-align: top; - position: relative; - bottom: 0.2rem; -} - -sub { - vertical-align: bottom; - position: relative; - top: 0.2rem; -} - -hr { - border: 1.5px solid var(--table-cell-border-color); -} - -.iframeWrap { - position: relative; - display: block; - padding-top: 56.25%; -} - -.iframeWrap iframe { - position: absolute; - top: 0; - left: 0; - height: 100% !important; - width: 100% !important; -} - -blockquote { - margin-inline-start: 0; - margin-inline-end: 0; - padding-inline-start: 15px; - border-inline-start: 3px solid var(--block-quote-border-color); -} - -/* Feed Specific */ - -.feedbin--article-wrap { - border-top: 1px solid var(--header-table-border-color); -} - -/* Twitter */ - -.twitterAvatar { - vertical-align: middle; - border-radius: 4px; - height: 1.7em; - width: 1.7em; -} - -.twitterUsername { - line-height: 1.2; - margin-left: 4px; - display: inline-block; - vertical-align: middle; -} - -.twitterScreenName { - font-size: 66%; -} - -.twitterTimestamp { - font-size: 66%; -} - -/* Newsfoot theme for light mode (default) */ -.newsfoot-footnote-popover { - background: #ccc; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5), 0 3px 6px rgba(0, 0, 0, 0.25); - color: black; - padding: 1px; -} - -.newsfoot-footnote-popover-arrow { - background: #fafafa; - border: 1px solid #ccc; -} - -.newsfoot-footnote-popover-inner { - background: #fafafa; -} - -body a.footnote, -body a.footnote:visited, -.newsfoot-footnote-popover + a.footnote:hover { - background: #aaa; - color: white; - transition: background-color 200ms ease-out; -} - -a.footnote:hover, -.newsfoot-footnote-popover + a.footnote { - background: #666; - transition: background-color 200ms ease-out; -} - -/* Newsfoot theme for dark mode */ -@media screen and (prefers-color-scheme: dark) { - .newsfoot-footnote-popover { - background: #444; - color: rgb(224, 224, 224); - } - - .newsfoot-footnote-popover-arrow { - background: #242424; - border: 1px solid #444; - } - - .newsfoot-footnote-popover-inner { - background: #242424; - } - - body a.footnote, - body a.footnote:visited, - .newsfoot-footnote-popover + a.footnote:hover { - background: #aaa; - color: white; - transition: background-color 200ms ease-out; - } - - a.footnote:hover, - .newsfoot-footnote-popover + a.footnote { - background: #666; - transition: background-color 200ms ease-out; - } - -} - -/* iOS Specific */ -@supports (-webkit-touch-callout: none) { - - body { - margin-top: 3px; - margin-bottom: 20px; - padding-left: 20px; - padding-right: 20px; - - font-family: 'Atkinson Hyperlegible', -apple-system; - font-size: 135%; - - word-break: break-word; - -webkit-hyphens: auto; - -webkit-text-size-adjust: none; - } - - :root { - color-scheme: light dark; - font: font-family: 'Atkinson Hyperlegible', -apple-system-body; - /* The font-size is replaced at runtime by the dynamic type size */ - font-size: [[font-size]]px; - --primary-accent-color: #086AEE; - --secondary-accent-color: #086AEE; - --block-quote-border-color: rgba(8, 106, 238, 0.75); - } - - @media(prefers-color-scheme: dark) { - :root { - --primary-accent-color: #2D80F1; - --secondary-accent-color: #5E9EF4; - --block-quote-border-color: rgba(94, 158, 244, 0.75); - --header-table-border-color: rgba(255, 255, 255, 0.2); - } - } - - body a, body a:visited { - color: var(--secondary-accent-color); - } - - body .header { - font: font-family: 'Atkinson Hyperlegible', -apple-system-body; - font-size: 135%; - } - - body .header a:link, body .header a:visited { - color: var(--primary-accent-color); - } - - pre { - border: 1px solid var(--secondary-accent-color); - padding: 5px; - } - - .nnw-overflow table { - border: 1px solid var(--secondary-accent-color); - } - - .articleTitle h1 { - font-size: 1.25em; - } -} - -/* macOS Specific */ -@supports not (-webkit-touch-callout: none) { - - body { - margin-top: 20px; - margin-bottom: 64px; - padding-left: 48px; - padding-right: 48px; - font-family: 'Atkinson Hyperlegible', -apple-system; - } - - .smallText { - font-size: 22px; - } - - .mediumText { - font-size: 24px; - } - - .largeText { - font-size: 26px; - } - - .xlargeText { - font-size: 28px; - } - - .xxlargeText { - font-size: 30px; - } - - :root { - color-scheme: light dark; - --accent-color: rgba(8, 106, 238, 1); - --block-quote-border-color: rgba(8, 106, 238, .50); - } - - @media(prefers-color-scheme: dark) { - :root { - --accent-color: rgba(94, 158, 244, 1); - --block-quote-border-color: rgba(94, 158, 244, .50); - --header-table-border-color: rgba(255, 255, 255, 0.1); - } - } - - body .header { - font-size: 135%; - } - - body .articleTitle { - font-size: 135%; - } - - body .articleDateline { - font-size: 135%; - } - - body .externalLink { - font-size: 135%; - } - - body a, body a:visited { - color: var(--accent-color); - } - - pre { - border: 1px solid var(--accent-color); - padding: 10px; - } - - .nnw-overflow table { - border: 1px solid var(--accent-color); - } - -} diff --git a/Resources/Themes/NewsFax.nnwtheme/Info.plist b/Resources/Themes/NewsFax.nnwtheme/Info.plist deleted file mode 100644 index 68e2fb253..000000000 --- a/Resources/Themes/NewsFax.nnwtheme/Info.plist +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Name - NewsFax - ThemeIdentifier - com.mynameisstuart.themes.newsfax - CreatorHomePage - https://mynameisstuart.com/ - CreatorName - Stuart Breckenridge - Version - 3 - - diff --git a/Resources/Themes/NewsFax.nnwtheme/License.md b/Resources/Themes/NewsFax.nnwtheme/License.md deleted file mode 100644 index 30077a880..000000000 --- a/Resources/Themes/NewsFax.nnwtheme/License.md +++ /dev/null @@ -1,20 +0,0 @@ -The NewsFax themes uses the ModeSeven font throughout, which is available as Freeware. It also includes additional edits from [schriftgestalt](https://github.com/schriftgestalt). - -Find out more [here](https://www.fontspace.com/modeseven-font-f2369). - -ModeSeven is based on the bitmap font in Teletext televisions, -1980s-vintage Videotext terminals (such as the Prestel system used in -the UK), and the BBC Micro computer. (The name derives from the BBC -Micro screen mode which used the teletext character generator.) - -This font looks "natural" at a size of 20 pixels, or any multiple thereof. -However, it has been hinted as to scale as well as an ex-bitmap font -can be expected to. - -This font was created by hand with Fontographer 4.1.2 on a Macintosh. -The character definitions were worked out from a bitmap version of the -Teletext font created by James Fidell, and included in xbeeb (a BBC -Micro emulator for UNIX/X11). The spacing of the original has been -preserved, which is why many character shapes are aligned to the right -of their cells. - diff --git a/Resources/Themes/NewsFax.nnwtheme/stylesheet.css b/Resources/Themes/NewsFax.nnwtheme/stylesheet.css deleted file mode 100644 index 442ca3cbe..000000000 --- a/Resources/Themes/NewsFax.nnwtheme/stylesheet.css +++ /dev/null @@ -1,621 +0,0 @@ -/* Custom Fonts */ -@font-face { - font-family: "ModeSeven"; - /* Add other properties here, as needed. For example: */ - /* - font-weight: 100 900; - font-style: normal italic; - */ - src: url(data:font/ttf;base64,AAEAAAANAIAAAwBQRFNJRwAAAAEAAGFgAAAACEdERUYP9Q7oAABW2AAAAIpHUE9T7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AAeaAAAIUAAAB3AAAAhQAAAHmgAACFAAAAAAB6YIUAAAAAAHpghQAAAAAAemCFAAAAAAB6YHlAAAAAAHpghQAAAAAAemB44AAAAAB6YIUAAAB9oHoAhiB3YAAAemCFAAAAfaAAAIYgAAB9oAAAhiAAAH2gAACGIAAAfaAAAIYgAAB9oAAAhiAAAH5AAACGIAAAfaAAAIYgAAB9oAAAhiAAAH2gAACGIAAAfaAAAIYgAAB+QAAAhiAAAHfAAACGIHiAd8AAAIYgeIB3wAAAhiB4gHggAACGIHiAeaB6AIUAAAB5oHoAhQAAAHmgegCFAAAAeaB6AHlAAAB5oHoAhQAAAHmgegB44AAAeaB6AIUAAAB5oHoAhQAAAHmgegCFAAAAeaB6AIUAAAB5oAAAhQAAAAAAAACFAAAAAAAAAIUAAAAAAAAAhQAAAAAAAAB5QAAAAAAAAIUAAAB5oAAAhQAAAAAAAACFAAAAAAAAAIUAAAAAAAAAhQAAAAAAAAB5QAAAAAAAAIUAAAAAAAAAhQAAAHmgAACFAAAAeaAAAIUAAAB5oAAAhQAAAHmgAACFAAAAeaB6AIUAAAAAAHpghQAAAAAQCWArwAAQFeA7YAAQJYArwAAQEsArwAAQFeA4QAAQImArwAAQFeA1IAAQFe/zgAAQEsAyAAAQFe/qIAAQJYAfQAAQGQAAAAAQGQ/qIAAQGQArwAAQFeAu4AAQFeArwAAQFeAAAAAQImAAAAAQHCAAAABgAQAAEACgAAAAEADAAUAAEAGgAqAAEAAgFRAVIAAQABAVEAAgAAAAoAAAAKAAEBLAAAAAEABAABASz+ogAGABAAAQAKAAEAAQAMABwAAQAqAHQAAgACAUQBSAAAAUoBUAAFAAEABQFEAUgBUAFUAVgADAAAAD4AAABEAAAAMgAAADgAAAA+AAAARAAAAEQAAABEAAAARAAAAEQAAABEAAAARAABAV4B9AABAPoB9AABAMgB9AABASwB9AAFABIAGAAMABIAGAABASwDUgABAMgCvAABAMgC7gAAAAEAAAAA); -} - - -body { - margin-left: auto; - margin-right: auto; - background: black; - word-wrap: break-word; - max-width: 44em; - color: white; -} - -.feedHeader { - margin: auto; - text-align: center; -} - -.feedHeader img { - margin: auto; - display: block; - padding-top: 1em; - padding-bottom: 1em; -} - -th.newsfax { - color: yellow; - width: 22.5%; -} - -.svg-inline--fa { - height: 1em; - width: 1em; - vertical-align: middle; -} - -a { - text-decoration: none; - font-weight: bolder; -} -a:hover { - text-decoration: underline; -} -.feedlink { - font-weight: bold; -} -.headerTable { - width: 100%; - height: 68px; -} - -.newsfax-footer { - padding-top: 40px; -} - -.newsfax-footer-cell-red a { - color: red; -} - -.newsfax-footer-cell-green a { - color: green; -} - -.newsfax-footer-cell-yellow a { - color: yellow; -} - -.newsfax-footer-cell-blue a { - color: cornflowerblue; -} - - -pre { - padding: 5px; - color: white; -} - -.systemMessage { - position: absolute; - top: 45%; - left: 50%; - transform: translateX(-55%) translateY(-50%); - -webkit-user-select: none; - cursor: default; -} - -:root { - --header-table-border-color: rgba(0, 0, 0, 0.1); - --header-color: rgba(0, 0, 0, 0.3); - --body-code-color: lightgray; - --system-message-color: #cbcbcb; - --feedlink-color: rgba(0, 182, 255, 0.6); - --article-title-color: #fff; - --article-date-color: rgba(0, 0, 0, 0.3); - --table-cell-border-color: lightgray; -} - -body .headerTable { - border-bottom: 1px solid var(--header-table-border-color); - color: var(--header-color); -} -body .header { - color: var(--header-color); -} -body .header a:link, .header a:visited { - color: var(--header-color); -} - -body code, body pre { - color: var(--body-code-color); -} - -body > .systemMessage { - color: var(--system-message-color); -} - -.feedlink a:link, .feedlink a:visited { - color: var(--feedlink-color); -} - -.avatar img { - border-: 4px; - display: none; -} - -.feedIcon { - border-radius: 4px; - display: none; -} -.rightAlign { - text-align: end; -} -.leftAlign { - text-align: start; -} - -.articleTitle a:link, .articleTitle a:visited, .articleTitle h1 { - color: var(--article-title-color); - margin-top: 26px; - padding-bottom: 12px; - padding-top: 10px; - text-align: center; - text-transform: uppercase; - margin: auto; - font-family: ModeSeven, ui-serif; -} - -.articleDateline { - color: rgba(124, 124, 124, 1); - margin-bottom: 5px; - text-align: center; - padding-top: 1em; -} - -.articleDateline a:link, .articleDateline a:visited { - color: rgba(166, 166, 166, 1); - font-weight: normal; - padding-top: 1em; - text-align: center; -} - -.articleDatelineTitle { - color: rgba(124, 124, 124, 1); - margin-bottom: 5px; - font-weight: normal; -} - -.articleDatelineTitle a:link, .articleDatelineTitle a:visited { - color: var(--article-title-color); -} - -.externalLink { - margin-bottom: 5px; - font-style: italic; - width: 100%; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - text-align: center; -} - - - -.articleBody { - margin-top: 20px; - line-height: 1.6em; -} - -h1 { - line-height: 1.15em; - font-weight: bold; - padding-bottom: 0; - margin-bottom: 5px; -} - -pre { - max-width: 100%; - margin: 0; - overflow: auto; - overflow-y: hidden; - word-wrap: normal; - word-break: normal; -} - -pre { - line-height: 1.4286em; -} - -code, pre { - font-family: 'ModeSeven', SF Mono, Menlo, "Courier New", Courier, monospace; - font-size: 0.95em; - -webkit-hyphens: none; -} - -pre code { - letter-spacing: -.027em; - font-size: 0.9375em; -} - -.nnw-overflow { - overflow-x: auto; -} -/* - Instead of the last-child bits, border-collapse: collapse - could have been used. However, then the inter-cell borders - overlap the table border, which looks bad. - */ -.nnw-overflow table { - margin-bottom: 1px; - border-spacing: 0; - border: 1px solid var(--secondary-accent-color); - font-size: inherit; -} -.nnw-overflow table table { - margin-bottom: 0; - border: none; -} -.nnw-overflow td, .nnw-overflow th { - -webkit-hyphens: none; - word-break: normal; - border: 1px solid var(--table-cell-border-color); - border-top: none; - border-left: none; - padding: 5px; -} - -.nnw-overflow tr :matches(td, th):last-child { - border-right: none; -} - -.nnw-overflow :matches(thead, tbody, tfoot):last-child > tr:last-child :matches(td, th) { - border-bottom: none; -} -.nnw-overflow td pre { - border: none; - padding: 0; -} -.nnw-overflow table[border="0"] { - border-width: 0; -} - -img, figure, video, div, object { - max-width: 100%; - height: auto !important; - margin: 0 auto; -} - -iframe { - max-width: 100%; - margin: 0 auto; -} - -iframe.nnw-constrained { - max-height: 50vw; -} - -figure { - margin-bottom: 1em; - margin-top: 1em; -} - -figcaption { - font-size: 14px; - line-height: 1.3em; -} - -sup { - vertical-align: top; - position: relative; - bottom: 0.2rem; -} - -sub { - vertical-align: bottom; - position: relative; - top: 0.2rem; -} - -hr { - border: none; - background-color: var(--table-cell-border-color); - height: 1px; - margin-top: 1em; -} - -.iframeWrap { - position: relative; - display: block; - padding-top: 56.25%; -} - -.iframeWrap iframe { - position: absolute; - top: 0; - left: 0; - height: 100% !important; - width: 100% !important; -} - -/* @media (prefers-color-scheme: light) { - blockquote { - background: color(srgb 0.947 0.947 0.947); - border-radius: 4px; - margin: 1.5em 0; - padding: 1rem; - color: color(srgb 0.383 0.383 0.383); - font-size: 0.95rem; - } - - pre { - background: color(srgb 0.947 0.947 0.947); - } - - p code { - background: color(srgb 0.947 0.947 0.947); - padding: 0.2em; - border-radius: 4px; - } -} */ - -blockquote { - background: rgba(49, 49, 49, 1); - margin: 1.5em 0; - padding: 1em; - color: rgba(195, 195, 195, 1); - font-size: 0.95rem; - } - - pre { - background: rgba(49, 49, 49, 1); - color: white; - } - - p code { - background: rgba(49, 49, 49, 1); - padding: 0.2em; - border-radius: 4px; - color: white; - } - -blockquote > blockquote { - padding-left: 1em; - padding-top: 0em; - padding-bottom: 0em; - font-style: italic; -} - - -blockquote > *:first-child { - margin-block-start: 0px; -} - -blockquote > *:last-child { - margin-block-end: 0px; -} - - -/* Feed Specific */ - -.feedbin--article-wrap { - border-top: 1px solid var(--header-table-border-color); -} - -/* Hide the external link at the bottom of Daring Fireball posts */ - -.x-netnewswire-hide { - display: none; -} - -/* see removeWpSmiley; this rule is kept in case a wp-smiley is encountered without alt text */ - -.wp-smiley { - height: 1em; - max-height: 1em; -} - -/* Twitter */ - -.twitterAvatar { - vertical-align: middle; - border-radius: 4px; - height: 1.7em; - width: 1.7em; -} - -.twitterUsername { - line-height: 1.2; - margin-left: 4px; - display: inline-block; - vertical-align: middle; -} - -.twitterScreenName { - font-size: 66%; -} - -.twitterTimestamp { - font-size: 66%; -} - -/*Block ads and junk*/ - -iframe[src*="feedads"], -iframe[src*="doubleclick"], -iframe[src*="plusone.google"] { - display: none !important; -} - -a[href*=".ads."], -a[href*="feedads"], -a[href*="doubleclick"], -a[href*="//ads."], -a[href*="api.tweetmeme"], -a[href*="delicious.com/post?"], -a[href*="digg.com/submit?"], -a[href*="google.com/bookmarks/mark?"], -a[href*="posterous.com/share?"], -a[href*="tumblr.com/share?"], -a[href*="linkedin.com/shareArticle?"], -a[href*="facebook.com/share.php?"], -a[href*="http://twitter.com/home?"], -a[href*="addtoany.com/share_save"] { - display: none !important; -} - -img[src*=".ads."], -img[src*="//ads."], -img[src*="doubleclick"], -img[src*="feedads"], -img[src*="feedburner"], -img[src*="feedblitz"], -img[src*="share-buttons"] { - display: none !important; -} - -/* light / default */ -.newsfoot-footnote-popover { - background: #ccc; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5), 0 3px 6px rgba(0, 0, 0, 0.25); - color: black; - padding: 1px; -} -.newsfoot-footnote-popover-arrow { - background: #fafafa; - border: 1px solid #ccc; -} -.newsfoot-footnote-popover-inner { - background: #fafafa; -} -body a.footnote, -body a.footnote:visited, -.newsfoot-footnote-popover + a.footnote:hover { - background: #aaa; - color: white; - transition: background-color 200ms ease-out; -} -a.footnote:hover, -.newsfoot-footnote-popover + a.footnote { - background: #666; - transition: background-color 200ms ease-out; -} - -/* dark */ -@media screen and (prefers-color-scheme: dark) { - .newsfoot-footnote-popover { - background: #444; - color: rgb(224, 224, 224); - } - .newsfoot-footnote-popover-arrow { - background: #242424; - border: 1px solid #444; - } - .newsfoot-footnote-popover-inner { - background: #242424; - } - body a.footnote, - body a.footnote:visited, - .newsfoot-footnote-popover + a.footnote:hover { - background: #aaa; - color: white; - transition: background-color 200ms ease-out; - } - a.footnote:hover, - .newsfoot-footnote-popover + a.footnote { - background: #666; - transition: background-color 200ms ease-out; - } -} - -/* iOS Specific */ -@supports (-webkit-touch-callout: none) { - - body { - margin-top: 3px; - margin-bottom: 20px; - padding-left: 20px; - padding-right: 20px; - font-family: 'ModeSeven', -apple-system; - } - - :root { - --primary-accent-color:rgba(110, 227, 231, 1); - --secondary-accent-color: rgba(110, 227, 231, 1); - --block-quote-border-color: rgba(94, 158, 244, 0.75); - --header-table-border-color: rgba(255, 255, 255, 0.2); - } - body a, body a:visited, body a * { - color: var(--secondary-accent-color); - } - body .header { - font: -apple-system-body; - font-size: [[font-size]]px; - } - body .header a:link, body .header a:visited { - color: var(--primary-accent-color); - } - - .articleTitle h1 { - font-size: 1.5em; - } - - .avatar img { - border-radius: 4px; - } - - .nnw-overflow table { - border: none; - } - - .activityIndicatorWrap { - position: relative; - } - - .activityIndicator { - z-index: 1; - width: 64px; - height: 64px; - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - } - -} - -/* macOS Specific */ -@supports not (-webkit-touch-callout: none) { - - body { - margin-top: 20px; - margin-bottom: 64px; - padding-left: 48px; - padding-right: 48px; - font-family: 'ModeSeven', -apple-system; - } - - .smallText { - font-size: 14px; - } - - .mediumText { - font-size: 16px; - } - - .largeText { - font-size: 18px; - } - - .xlargeText { - font-size: 20px; - } - - .xxlargeText { - font-size: 22px; - } - - :root { - --accent-color: rgba(110, 227, 231, 1); - --block-quote-border-color: rgba(94, 158, 244, .50); - --header-table-border-color: rgba(255, 255, 255, 0.1); - } - - - - body a, body a:visited, body a * { - color: var(--accent-color); - } - - .nnw-overflow table { - //border: 1px solid var(--accent-color); - } - -} diff --git a/Resources/Themes/Promenade.nnwtheme/Info.plist b/Resources/Themes/Promenade.nnwtheme/Info.plist deleted file mode 100644 index 24ec5ca47..000000000 --- a/Resources/Themes/Promenade.nnwtheme/Info.plist +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Name - Promenade - ThemeIdentifier - com.mynameisstuart.themes.promenade - CreatorHomePage - https://mynameisstuart.com/ - CreatorName - Stuart Breckenridge - Version - 14 - - diff --git a/Resources/Themes/Promenade.nnwtheme/stylesheet.css b/Resources/Themes/Promenade.nnwtheme/stylesheet.css deleted file mode 100644 index 5a2b589ec..000000000 --- a/Resources/Themes/Promenade.nnwtheme/stylesheet.css +++ /dev/null @@ -1,610 +0,0 @@ -body { - margin-left: auto; - margin-right: auto; - - word-wrap: break-word; - max-width: 44em; -} - -.feedHeader { - margin: auto; - text-align: center; -} - -.feedHeader img { - margin: auto; - display: block; - padding-top: 1em; - padding-bottom: 1em; -} - -.svg-inline--fa { - height: 1em; - width: 1em; - vertical-align: middle; -} - -a { - text-decoration: none; - font-weight: bold; -} -a:hover { - text-decoration: underline; -} -.feedlink { - font-weight: bold; -} -.headerTable { - width: 100%; - height: 68px; -} - -img { - border-radius: 4px; -} - -pre { - padding: 5px; - border-radius: 4px; -} - -.systemMessage { - position: absolute; - top: 45%; - left: 50%; - transform: translateX(-55%) translateY(-50%); - -webkit-user-select: none; - cursor: default; -} - -:root { - --header-table-border-color: rgba(0, 0, 0, 0.1); - --header-color: rgba(0, 0, 0, 0.3); - --body-code-color: #666; - --system-message-color: #cbcbcb; - --feedlink-color: rgba(255, 0, 0, 0.6); - --article-title-color: #333; - --article-date-color: rgba(0, 0, 0, 0.3); - --table-cell-border-color: lightgray; -} - -@media(prefers-color-scheme: dark) { - :root { - --header-color: rgba(94, 158, 244, 1); - --body-code-color: #b2b2b2; - --system-message-color: #5f5f5f; - --feedlink-color: rgba(94, 158, 244, 1); - --article-title-color: #e0e0e0; - --article-date-color: rgba(255, 255, 255, 0.5); - --table-cell-border-color: dimgray; - } -} - -body .headerTable { - border-bottom: 1px solid var(--header-table-border-color); - color: var(--header-color); -} -body .header { - color: var(--header-color); -} -body .header a:link, .header a:visited { - color: var(--header-color); -} - -body code, body pre { - color: var(--body-code-color); -} - -body > .systemMessage { - color: var(--system-message-color); -} - -.feedlink a:link, .feedlink a:visited { - color: var(--feedlink-color); -} - -.avatar img { - border-radius: 4px; -} - -.feedIcon { - border-radius: 4px; -} -.rightAlign { - text-align: end; -} -.leftAlign { - text-align: start; -} - -.articleTitle a:link, .articleTitle a:visited, .articleTitle h1 { - color: var(--article-title-color); - margin-top: 26px; - padding-bottom: 12px; - text-align: center; - margin: auto; - font-family: Charter, ui-serif; -} - -.articleDateline { - color: rgba(124, 124, 124, 1); - margin-bottom: 5px; - text-align: center; - padding-top: 1em; -} - -.articleDateline a:link, .articleDateline a:visited { - color: rgba(166, 166, 166, 1); - font-weight: normal; - padding-top: 1em; - text-align: center; -} - -.articleDatelineTitle { - color: rgba(124, 124, 124, 1); - margin-bottom: 5px; - font-weight: normal; -} - -.articleDatelineTitle a:link, .articleDatelineTitle a:visited { - color: var(--article-title-color); -} - -.externalLink { - margin-bottom: 5px; - font-style: italic; - width: 100%; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - text-align: center; -} - - - -.articleBody { - margin-top: 20px; - line-height: 1.6em; -} - -h1 { - line-height: 1.15em; - font-weight: bold; - padding-bottom: 0; - margin-bottom: 5px; -} - -pre { - max-width: 100%; - margin: 0; - overflow: auto; - overflow-y: hidden; - word-wrap: normal; - word-break: normal; -} - -pre { - line-height: 1.4286em; -} - -code, pre { - font-family: "SF Mono", Menlo, "Courier New", Courier, monospace; - font-size: 0.95em; - -webkit-hyphens: none; -} - -pre code { - letter-spacing: -.027em; - font-size: 0.9375em; -} - -.nnw-overflow { - overflow-x: auto; -} -/* - Instead of the last-child bits, border-collapse: collapse - could have been used. However, then the inter-cell borders - overlap the table border, which looks bad. - */ -.nnw-overflow table { - margin-bottom: 1px; - border-spacing: 0; - border: 1px solid var(--secondary-accent-color); - font-size: inherit; -} -.nnw-overflow table table { - margin-bottom: 0; - border: none; -} -.nnw-overflow td, .nnw-overflow th { - -webkit-hyphens: none; - word-break: normal; - border: 1px solid var(--table-cell-border-color); - border-top: none; - border-left: none; - padding: 5px; -} - -.nnw-overflow tr :matches(td, th):last-child { - border-right: none; -} - -.nnw-overflow :matches(thead, tbody, tfoot):last-child > tr:last-child :matches(td, th) { - border-bottom: none; -} -.nnw-overflow td pre { - border: none; - padding: 0; -} -.nnw-overflow table[border="0"] { - border-width: 0; -} - -img, figure, video, div, object { - max-width: 100%; - height: auto !important; - margin: 0 auto; -} - -iframe { - max-width: 100%; - margin: 0 auto; -} - -iframe.nnw-constrained { - max-height: 50vw; -} - -figure { - margin-bottom: 1em; - margin-top: 1em; -} - -figcaption { - font-size: 14px; - line-height: 1.3em; -} - -sup { - vertical-align: top; - position: relative; - bottom: 0.2rem; -} - -sub { - vertical-align: bottom; - position: relative; - top: 0.2rem; -} - -hr { - border: none; - background-color: var(--table-cell-border-color); - height: 1px; - margin-top: 1em; -} - -.iframeWrap { - position: relative; - display: block; - padding-top: 56.25%; -} - -.iframeWrap iframe { - position: absolute; - top: 0; - left: 0; - height: 100% !important; - width: 100% !important; -} - -@media (prefers-color-scheme: light) { - blockquote { - background: color(srgb 0.947 0.947 0.947); - border-radius: 4px; - margin: 1.5em 0; - padding: 1rem; - color: color(srgb 0.383 0.383 0.383); - font-size: 0.95rem; - } - - pre { - background: color(srgb 0.947 0.947 0.947); - } - - p code { - background: color(srgb 0.947 0.947 0.947); - padding: 0.2em; - border-radius: 4px; - } -} - -@media (prefers-color-scheme: dark) { - blockquote { - background: rgba(49, 49, 49, 1); - border-radius: 4px; - margin: 1.5em 0; - padding: 1em; - color: rgba(195, 195, 195, 1); - font-size: 0.95rem; - } - - pre { - background: rgba(49, 49, 49, 1); - } - - p code { - background: rgba(49, 49, 49, 1); - padding: 0.2em; - border-radius: 4px; - } -} - -blockquote > blockquote { - padding-left: 1em; - padding-top: 0em; - padding-bottom: 0em; - font-style: italic; -} - - -blockquote > *:first-child { - margin-block-start: 0px; -} - -blockquote > *:last-child { - margin-block-end: 0px; -} - - -/* Feed Specific */ - -.feedbin--article-wrap { - border-top: 1px solid var(--header-table-border-color); -} - -/* Hide the external link at the bottom of Daring Fireball posts */ - -.x-netnewswire-hide { - display: none; -} - -/* see removeWpSmiley; this rule is kept in case a wp-smiley is encountered without alt text */ - -.wp-smiley { - height: 1em; - max-height: 1em; -} - -/* Twitter */ - -.twitterAvatar { - vertical-align: middle; - border-radius: 4px; - height: 1.7em; - width: 1.7em; -} - -.twitterUsername { - line-height: 1.2; - margin-left: 4px; - display: inline-block; - vertical-align: middle; -} - -.twitterScreenName { - font-size: 66%; -} - -.twitterTimestamp { - font-size: 66%; -} - -/*Block ads and junk*/ - -iframe[src*="feedads"], -iframe[src*="doubleclick"], -iframe[src*="plusone.google"] { - display: none !important; -} - -a[href*=".ads."], -a[href*="feedads"], -a[href*="doubleclick"], -a[href*="//ads."], -a[href*="api.tweetmeme"], -a[href*="delicious.com/post?"], -a[href*="digg.com/submit?"], -a[href*="google.com/bookmarks/mark?"], -a[href*="posterous.com/share?"], -a[href*="tumblr.com/share?"], -a[href*="linkedin.com/shareArticle?"], -a[href*="facebook.com/share.php?"], -a[href*="http://twitter.com/home?"], -a[href*="addtoany.com/share_save"] { - display: none !important; -} - -img[src*=".ads."], -img[src*="//ads."], -img[src*="doubleclick"], -img[src*="feedads"], -img[src*="feedburner"], -img[src*="feedblitz"], -img[src*="share-buttons"] { - display: none !important; -} - -/* light / default */ -.newsfoot-footnote-popover { - background: #ccc; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5), 0 3px 6px rgba(0, 0, 0, 0.25); - color: black; - padding: 1px; -} -.newsfoot-footnote-popover-arrow { - background: #fafafa; - border: 1px solid #ccc; -} -.newsfoot-footnote-popover-inner { - background: #fafafa; -} -body a.footnote, -body a.footnote:visited, -.newsfoot-footnote-popover + a.footnote:hover { - background: #aaa; - color: white; - transition: background-color 200ms ease-out; -} -a.footnote:hover, -.newsfoot-footnote-popover + a.footnote { - background: #666; - transition: background-color 200ms ease-out; -} - -/* dark */ -@media screen and (prefers-color-scheme: dark) { - .newsfoot-footnote-popover { - background: #444; - color: rgb(224, 224, 224); - } - .newsfoot-footnote-popover-arrow { - background: #242424; - border: 1px solid #444; - } - .newsfoot-footnote-popover-inner { - background: #242424; - } - body a.footnote, - body a.footnote:visited, - .newsfoot-footnote-popover + a.footnote:hover { - background: #aaa; - color: white; - transition: background-color 200ms ease-out; - } - a.footnote:hover, - .newsfoot-footnote-popover + a.footnote { - background: #666; - transition: background-color 200ms ease-out; - } -} - -/* iOS Specific */ -@supports (-webkit-touch-callout: none) { - - body { - margin-top: 3px; - margin-bottom: 20px; - padding-left: 20px; - padding-right: 20px; - } - - :root { - color-scheme: light dark; - font-family: 'Avenir-Book', -apple-system-body; - font-size: [[font-size]]px; - --primary-accent-color: #086AEE; - --secondary-accent-color: #086AEE; - --block-quote-border-color: rgba(8, 106, 238, 0.75); - } - - @media(prefers-color-scheme: dark) { - :root { - --primary-accent-color: #2D80F1; - --secondary-accent-color: #5E9EF4; - --block-quote-border-color: rgba(94, 158, 244, 0.75); - --header-table-border-color: rgba(255, 255, 255, 0.2); - } - } - - body a, body a:visited, body a * { - color: var(--secondary-accent-color); - } - body .header { - font: -apple-system-body; - font-size: [[font-size]]px; - } - body .header a:link, body .header a:visited { - color: var(--primary-accent-color); - } - - .articleTitle h1 { - font-size: 1.5em; - } - - .avatar img { - border-radius: 4px; - } - - .nnw-overflow table { - border: none; - } - - .activityIndicatorWrap { - position: relative; - } - - .activityIndicator { - z-index: 1; - width: 64px; - height: 64px; - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - } -} - -/* macOS Specific */ -@supports not (-webkit-touch-callout: none) { - - body { - margin-top: 20px; - margin-bottom: 64px; - padding-left: 48px; - padding-right: 48px; - font-family: 'Avenir', -apple-system; - } - - .smallText { - font-size: 14px; - } - - .mediumText { - font-size: 16px; - } - - .largeText { - font-size: 18px; - } - - .xlargeText { - font-size: 20px; - } - - .xxlargeText { - font-size: 22px; - } - - :root { - color-scheme: light dark; - --accent-color: rgba(8, 106, 238, 1); - --block-quote-border-color: rgba(8, 106, 238, .50); - } - - @media(prefers-color-scheme: dark) { - :root { - --accent-color: rgba(94, 158, 244, 1); - --block-quote-border-color: rgba(94, 158, 244, .50); - --header-table-border-color: rgba(255, 255, 255, 0.1); - } - } - - body a, body a:visited, body a * { - color: var(--accent-color); - } - - .nnw-overflow table { - //border: 1px solid var(--accent-color); - } -} diff --git a/Resources/Themes/Sepia.nnwtheme/stylesheet.css b/Resources/Themes/Sepia.nnwtheme/stylesheet.css deleted file mode 100644 index 17ae8873d..000000000 --- a/Resources/Themes/Sepia.nnwtheme/stylesheet.css +++ /dev/null @@ -1,429 +0,0 @@ -/* Shared iOS and macOS CSS rules. Platform specific rules are at the bottom of this file. */ - -body { - margin-left: auto; - margin-right: auto; - word-wrap: break-word; - max-width: 44em; - background-color: rgb(248, 241, 227); - color: rgb(79, 50, 28); -} - -[href] { - text-decoration-style: underline; - text-decoration-color: var(--link-underline-color); - text-decoration-thickness: 1px; - text-underline-offset: 0.15em; -} -[href]:hover { - text-shadow: 0 1px rgba(255, 255, 255, 2); - opacity: 0.8; - color: color-mix(in hsl, var(--link-underline-color), firebrick 70%); -} - -#nnwImageIcon { - width: 32px; - height: 32px; - margin-right: 0.2em; -} - -.systemMessage { - position: absolute; - top: 45%; - left: 50%; - transform: translateX(-55%) translateY(-50%); - -webkit-user-select: none; - cursor: default; -} - -:root { - --header-table-border-color: rgba(0, 0, 0, 0.3); - --header-color: rgba(0, 0, 0, 0.5); - --body-code-color: #704214; - --system-message-color: #704214; - --feedlink-color: #704214; - --article-title-color: #704214; - --article-date-color: rgba(0, 0, 0, 0.5); - --table-cell-border-color: lightgray; - --primary-accent-color: #43350e; - --secondary-accent-color: #43350e; - --block-quote-border-color: rgba(0, 0, 0, 0.3); - --link-underline-color: color-mix(in hsl, currentColor, transparent 40%); - --link-underline-special: color-mix(in hsl, currentColor, transparent 80%) -} - -body a, -body a:visited, -body a * { - color: var(--secondary-accent-color); -} - -body > header { - border-bottom: 1px solid var(--header-table-border-color); - padding-bottom: 0.5rem; -} - -body > header a, -body > header a:link, -body > header a:visited { - color: var(--header-color); -} -body > header .headerTable { - width: 100%; -} -body > header .headerTable td, -body > header .headerTable th { - color: var(--header-color); - padding: 0.2em; - border: none; - font-family: sans-serif; - font-size: 0.9rem; -} -body > header .headerTable td.avatar { - width: 33%; -} - -body code, -body pre { - color: var(--body-code-color); -} - -body > .systemMessage { - color: var(--system-message-color); -} - -.headerContainer a[href] { - text-decoration-color: var(--link-underline-special); - color: var(--feedlink-color); -} - -.avatar img { - border-radius: 4px; -} - -.feedIcon { - border-radius: 4px; -} - -.rightAlign { - text-align: end; -} - -.leftAlign { - text-align: start; -} - -.articleTitle [href] { - text-decoration-color: transparent; - color: var(--article-title-color); - margin-top: 26px; -} - -.articleDateline { - margin-bottom: 5px; - font-weight: bold; -} - -.articleDateline [href] { - text-decoration-color: var(--link-underline-special); - color: var(--article-date-color); -} - -.articleDatelineTitle { - margin-bottom: 5px; - font-weight: bold; -} - -.articleDatelineTitle [href] { - color: var(--article-title-color); -} - -.externalLink { - margin-bottom: 5px; - font-style: italic; - width: 100%; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - - -.articleBody { - margin-top: 20px; - line-height: 1.6em; -} - -h1 { - line-height: 1.15em; - font-weight: bold; - padding-bottom: 0; - margin-bottom: 5px; -} - -pre { - max-width: 100%; - margin: 0; - overflow: auto; - overflow-y: hidden; - word-wrap: normal; - word-break: normal; -} - -pre { - line-height: 1.4286em; -} - -code, -pre { - font-family: "SF Mono", Menlo, "Courier New", Courier, monospace; - font-size: 0.85rem; - letter-spacing: -0.027em; - -webkit-hyphens: none; -} - -.nnw-overflow { - overflow-x: auto; -} - -/* - Instead of the last-child bits, border-collapse: collapse - could have been used. However, then the inter-cell borders - overlap the table border, which looks bad. - */ -.nnw-overflow table { - margin-bottom: 1px; - border-spacing: 0; - border: 1px solid var(--secondary-accent-color); - font-size: inherit; -} - -.nnw-overflow table table { - margin-bottom: 0; - border: none; -} - -.nnw-overflow td, -.nnw-overflow th { - -webkit-hyphens: none; - word-break: normal; - border: 1px solid var(--table-cell-border-color); - border-top: none; - border-left: none; - padding: 5px; -} - -.nnw-overflow tr :matches(td, th):last-child { - border-right: none; -} - -.nnw-overflow - :matches(thead, tbody, tfoot):last-child - > tr:last-child - :matches(td, th) { - border-bottom: none; -} - -.nnw-overflow td pre { - border: none; - padding: 0; -} - -.nnw-overflow table[border="0"] { - border-width: 0; -} - -img, -figure, -video, -div, -object { - max-width: 100%; - height: auto !important; - margin: 0 auto; -} - -iframe { - max-width: 100%; - margin: 0 auto; -} - -iframe.nnw-constrained { - max-height: 50vw; -} - -figure { - margin-bottom: 1em; - margin-top: 1em; -} - -figcaption { - font-size: 14px; - line-height: 1.3em; -} - -sup { - vertical-align: top; - position: relative; - bottom: 0.2rem; -} - -sub { - vertical-align: bottom; - position: relative; - top: 0.2rem; -} - -hr { - border: 1.5px solid var(--table-cell-border-color); -} - -.iframeWrap { - position: relative; - display: block; - padding-top: 56.25%; -} - -.iframeWrap iframe { - position: absolute; - top: 0; - left: 0; - height: 100% !important; - width: 100% !important; -} - -blockquote { - margin-inline-start: 0; - margin-inline-end: 0; - padding-inline-start: 15px; - border-inline-start: 3px solid var(--block-quote-border-color); -} - -/* Feed Specific */ - -.feedbin--article-wrap { - border-top: 1px solid var(--header-table-border-color); -} - -/* Twitter */ - -.twitterAvatar { - vertical-align: middle; - border-radius: 4px; - height: 1.7em; - width: 1.7em; -} - -.twitterUsername { - line-height: 1.2; - margin-left: 4px; - display: inline-block; - vertical-align: middle; -} - -.twitterScreenName { - font-size: 66%; -} - -.twitterTimestamp { - font-size: 66%; -} - -/* Newsfoot theme for light mode (default) */ -.newsfoot-footnote-popover { - background: #ccc; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5), 0 3px 6px rgba(0, 0, 0, 0.25); - color: #704214; - padding: 1px; -} - -.newsfoot-footnote-popover-arrow { - background: #fbf0d9; - border: 1px solid #ccc; -} - -.newsfoot-footnote-popover-inner { - background: #fbf0d9; -} - -body a.footnote, -body a.footnote:visited, -.newsfoot-footnote-popover + a.footnote:hover { - background: #aaa; - color: white; - transition: background-color 200ms ease-out; -} - -a.footnote:hover, -.newsfoot-footnote-popover + a.footnote { - background: #666; - transition: background-color 200ms ease-out; -} - -/* iOS Specific */ -@supports (-webkit-touch-callout: none) { - body { - margin-top: 3px; - margin-bottom: 20px; - padding-left: 20px; - padding-right: 20px; - - word-break: break-word; - -webkit-hyphens: auto; - -webkit-text-size-adjust: none; - font-family: Charter, Georgia, sans-serif; - font-size: [[font-size]]px; - } - - .articleTitle h1 { - font-size: 1.5em; - } - - pre { - border: 1px solid var(--secondary-accent-color); - padding: 5px; - } - - .nnw-overflow table { - border: 1px solid var(--secondary-accent-color); - } -} - -/* macOS Specific */ -@supports not (-webkit-touch-callout: none) { - body { - margin-top: 20px; - margin-bottom: 64px; - padding-left: 48px; - padding-right: 48px; - font-family: Charter, Georgia, sans-serif; - } - - .smallText { - font-size: 14px; - } - - .mediumText { - font-size: 16px; - } - - .largeText { - font-size: 18px; - } - - .xlargeText { - font-size: 20px; - } - - .xxlargeText { - font-size: 22px; - } - - pre { - border: 1px solid var(--primary-accent-color); - padding: 10px; - } - - .nnw-overflow table { - border: 1px solid var(--primary-accent-color); - } -} diff --git a/Resources/Themes/Tiqoe Dark.nnwtheme/Info.plist b/Resources/Themes/Tiqoe Dark.nnwtheme/Info.plist deleted file mode 100644 index 5b2d01752..000000000 --- a/Resources/Themes/Tiqoe Dark.nnwtheme/Info.plist +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Name - Tiqoe Dark - ThemeIdentifier - justin-reeves.net.themes.tiqoe.dark - CreatorHomePage - https://justin-reeves.net - CreatorName - Justin Reeves - Version - 1 - - diff --git a/Resources/Themes/Tiqoe Dark.nnwtheme/stylesheet.css b/Resources/Themes/Tiqoe Dark.nnwtheme/stylesheet.css deleted file mode 100644 index 649b69dff..000000000 --- a/Resources/Themes/Tiqoe Dark.nnwtheme/stylesheet.css +++ /dev/null @@ -1,457 +0,0 @@ -/* Shared iOS and macOS CSS rules. Platform specific rules are at the bottom of this file. */ - -body { - margin-left: auto; - margin-right: auto; - word-wrap: break-word; - max-width: 44em; - background-color: #17120f; - color: #c5c2c1; -} - -[href] { - text-decoration-style: underline; - text-decoration-color: var(--link-underline-color); - text-decoration-thickness: 1px; - text-underline-offset: 0.15em; -} - -[href]:has(img):hover { - opacity: 1; - } - -#nnwImageIcon { - width: 32px; - height: 32px; - margin-right: 0.2em; -} - -.systemMessage { - position: absolute; - top: 45%; - left: 50%; - transform: translateX(-55%) translateY(-50%); - -webkit-user-select: none; - cursor: default; -} - -:root { - color-scheme: dark; - --header-table-border-color: rgba(255, 255, 255, 0.3); - --header-color: rgba(255, 255, 255, 0.5); - --body-code-color: #c5c2c1; - --system-message-color: #c5c2c1; - --feedlink-color: rgba(255, 255, 255, 0.5); - --article-title-color: #c5c2c1; - --article-date-color: rgba(255, 255, 255, 0.5); - --table-cell-border-color: #43350e; - --primary-accent-color: #43350e; - --secondary-accent-color: #43350e; - --block-quote-border-color: rgba(255, 255, 255, 0.3); - --link-underline-color: color-mix(in hsl, currentColor, transparent 20%); - --link-underline-special: color-mix(in hsl, currentColor, transparent 40%) -} - -hr { - border: 1.5px solid dimgrey; -} - -body a, -body a:visited { - color: #bbb8b7; -} - -body :is(b, strong) { - color: color-mix(in hsl, var(--link-underline-color), firebrick 15%); -} - -a u { - text-decoration: none; -} - -body > header { - border-bottom: 1px solid var(--header-table-border-color); - padding-bottom: 0.5rem; -} - -body > header a, -body > header a:link, -body > header a:visited { - color: var(--header-color); -} -body > header .headerTable { - width: 100%; -} -body > header .headerTable td, -body > header .headerTable th { - color: var(--header-color); - padding: 0.2em; - border: none; - font-family: sans-serif; - font-size: 0.9rem; -} -body > header .headerTable td.avatar { - width: 33%; -} - -body code, -body pre { - color: var(--body-code-color); -} - -a code { - color: inherit; -} - -body > .systemMessage { - color: var(--system-message-color); -} - -.headerContainer a[href] { - text-decoration-color: var(--link-underline-special); - color: var(--feedlink-color); -} - -.avatar img { - border-radius: 4px; -} - -.feedIcon { - border-radius: 4px; -} - -.rightAlign { - text-align: end; -} - -.leftAlign { - text-align: start; -} - -.articleTitle [href] { - text-decoration-color: transparent; - color: var(--article-title-color); - margin-top: 26px; -} - -.articleDateline { - margin-bottom: 5px; - font-weight: bold; -} - -.articleDateline [href] { - text-decoration-color: var(--link-underline-special); - color: var(--article-date-color); -} - -.articleDatelineTitle { - margin-bottom: 5px; - font-weight: bold; -} - -.articleDatelineTitle [href] { - color: var(--article-title-color); -} - -.externalLink { - margin-bottom: 5px; - font-style: italic; - width: 100%; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - - -.articleBody { - margin-top: 20px; - line-height: 1.6em; -} - -h1 { - line-height: 1.15em; - font-weight: bold; - padding-bottom: 0; - margin-bottom: 5px; -} - -pre { - max-width: 100%; - margin: 0; - overflow: auto; - overflow-y: hidden; - word-wrap: normal; - word-break: normal; -} - -pre { - line-height: 1.4286em; -} - -code, -pre { - font-family: "SF Mono", Menlo, "Courier New", Courier, monospace; - font-size: 0.85rem; - letter-spacing: -0.027em; - -webkit-hyphens: none; -} - -.nnw-overflow { - overflow-x: auto; -} - -/* - Instead of the last-child bits, border-collapse: collapse - could have been used. However, then the inter-cell borders - overlap the table border, which looks bad. - */ -.nnw-overflow table { - margin-bottom: 1px; - border-spacing: 0; - border: 1px solid var(--secondary-accent-color); - font-size: inherit; -} - -.nnw-overflow table table { - margin-bottom: 0; - border: none; -} - -.nnw-overflow td, -.nnw-overflow th { - -webkit-hyphens: none; - word-break: normal; - border: 1px solid var(--table-cell-border-color); - border-top: none; - border-left: none; - padding: 5px; -} - -.nnw-overflow tr :matches(td, th):last-child { - border-right: none; -} - -.nnw-overflow - :matches(thead, tbody, tfoot):last-child - > tr:last-child - :matches(td, th) { - border-bottom: none; -} - -.nnw-overflow td pre { - border: none; - padding: 0; -} - -.nnw-overflow table[border="0"] { - border-width: 0; -} - -img, -figure, -video, -div, -object { - max-width: 100%; - height: auto !important; - margin: 0 auto; -} - -iframe { - max-width: 100%; - margin: 0 auto; -} - -iframe.nnw-constrained { - max-height: 50vw; -} - -figure { - margin-bottom: 1em; - margin-top: 1em; -} - -figcaption { - font-size: 14px; - line-height: 1.3em; -} - -sup { - vertical-align: top; - position: relative; - bottom: 0.2rem; -} - -sub { - vertical-align: bottom; - position: relative; - top: 0.2rem; -} - -.iframeWrap { - position: relative; - display: block; - padding-top: 56.25%; -} - -.iframeWrap iframe { - position: absolute; - top: 0; - left: 0; - height: 100% !important; - width: 100% !important; -} - -blockquote { - margin-inline-start: 0; - margin-inline-end: 0; - padding-inline-start: 15px; - border-inline-start: 3px solid var(--block-quote-border-color); -} - -/* Feed Specific */ - -.feedbin--article-wrap { - border-top: 1px solid var(--header-table-border-color); -} - -/* Twitter */ - -.twitterAvatar { - vertical-align: middle; - border-radius: 4px; - height: 1.7em; - width: 1.7em; -} - -.twitterUsername { - line-height: 1.2; - margin-left: 4px; - display: inline-block; - vertical-align: middle; -} - -.twitterScreenName { - font-size: 66%; -} - -.twitterTimestamp { - font-size: 66%; -} - -/* Newsfoot theme for light mode (default) */ -.newsfoot-footnote-popover { - background: #555; - box-shadow: 0 2px 4px rgba(255, 255, 255, 0.5), 0 3px 6px rgba(255, 255, 255, 0.25); - color: #c5c2c1; - padding: 1px; -} - -.newsfoot-footnote-popover-arrow { - background: #17120f; - border: 1px solid #555; -} - -.newsfoot-footnote-popover-inner { - background: #17120f; -} - -body a.footnote, -body a.footnote:visited, -.newsfoot-footnote-popover + a.footnote:hover { - background: #444; - color: #aaa; - transition: background-color 200ms ease-out; -} - -a.footnote:hover, -.newsfoot-footnote-popover + a.footnote { - background: #444; - transition: background-color 200ms ease-out; -} - -/* iOS Specific */ -@supports (-webkit-touch-callout: none) { - body { - margin-top: 3px; - margin-bottom: 20px; - padding-left: 20px; - padding-right: 20px; - - word-break: break-word; - -webkit-hyphens: auto; - -webkit-text-size-adjust: none; - font-family: Charter, Georgia, sans-serif; - font-size: [[font-size]]px; - } - - .articleTitle h1 { - font-size: 1.5em; - } - - pre { - border: 1px solid var(--secondary-accent-color); - padding: 5px; - } - - .nnw-overflow table { - border: 1px solid var(--secondary-accent-color); - } -} - -/* macOS Specific */ -@supports not (-webkit-touch-callout: none) { - body { - margin-top: 20px; - margin-bottom: 64px; - padding-left: 48px; - padding-right: 48px; - font-family: Charter, Georgia, sans-serif; - } - - .smallText { - font-size: 14px; - } - - .mediumText { - font-size: 16px; - } - - .largeText { - font-size: 18px; - } - - .xlargeText { - font-size: 20px; - } - - .xxlargeText { - font-size: 22px; - } - - pre { - border: 1px solid var(--primary-accent-color); - padding: 10px; - } - - .nnw-overflow table { - border: 1px solid var(--primary-accent-color); - } -} - -.image-link-expand .icon-container svg { - stroke: #aaa; -} - -.image-link-expand .icon-container:hover svg { - text-shadow: 0 1px rgba(0, 0, 0, 2); - opacity: 0.8; - stroke: color-mix(in hsl, var(--link-underline-color), firebrick 70%) -} - -[href]:hover, - .headerContainer a[href]:hover { - text-shadow: 0 1px rgba(0, 0, 0, 2); - opacity: 0.8; - color: color-mix(in hsl, var(--link-underline-color), firebrick 70%); -} diff --git a/Resources/Themes/Verdana Revival.nnwtheme/Info.plist b/Resources/Themes/Verdana Revival.nnwtheme/Info.plist deleted file mode 100644 index 4b547b5e9..000000000 --- a/Resources/Themes/Verdana Revival.nnwtheme/Info.plist +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Name - Verdana Revival - ThemeIdentifier - com.netnewswire.themes.verdanarevival - CreatorHomePage - http://netnewswire.com/ - CreatorName - Ranchero Software - Version - 1 - - diff --git a/Shared/AccountStats/AccountStatsViewModel.swift b/Shared/AccountStats/AccountStatsViewModel.swift index d1d72e5ee..b77a864cf 100644 --- a/Shared/AccountStats/AccountStatsViewModel.swift +++ b/Shared/AccountStats/AccountStatsViewModel.swift @@ -102,16 +102,21 @@ struct AccountStatsTotals { private extension AccountStatsViewModel { + /// A WAL-mode database also has -wal and -shm files. + static let databaseFileSuffixes = ["", "-wal", "-shm"] + func databaseSize(for account: Account) -> Int { let dataFolder = account.dataFolder as NSString let databaseNames = ["DB.sqlite3", "FeedSettings.db", "Sync.sqlite3"] var totalSize = 0 for databaseName in databaseNames { - let path = dataFolder.appendingPathComponent(databaseName) - if let attributes = try? FileManager.default.attributesOfItem(atPath: path), - let size = attributes[FileAttributeKey.size] as? Int { - totalSize += size + let databasePath = dataFolder.appendingPathComponent(databaseName) + for suffix in Self.databaseFileSuffixes { + if let attributes = try? FileManager.default.attributesOfItem(atPath: databasePath + suffix), + let size = attributes[FileAttributeKey.size] as? Int { + totalSize += size + } } } diff --git a/Shared/Activity/ActivityManager.swift b/Shared/Activity/ActivityManager.swift index 3f1758554..b438b84b3 100644 --- a/Shared/Activity/ActivityManager.swift +++ b/Shared/Activity/ActivityManager.swift @@ -51,7 +51,7 @@ import Images #endif init() { - NotificationCenter.default.addObserver(self, selector: #selector(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleFeedIconImageDidChange(_:)), name: .feedIconImageDidChange, object: nil) } func invalidateCurrentActivities() { @@ -171,8 +171,8 @@ import Images } #endif - @objc func feedIconDidBecomeAvailable(_ note: Notification) { - guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed, let activityFeedId = selectingActivity?.userInfo?[ArticlePathKey.feedID] as? String else { + @objc func handleFeedIconImageDidChange(_ notification: Notification) { + guard let feed = notification.userInfo?[UserInfoKey.feed] as? Feed, let activityFeedId = selectingActivity?.userInfo?[ArticlePathKey.feedID] as? String else { return } diff --git a/Shared/ActivityLog/ActivityLogViewModel.swift b/Shared/ActivityLog/ActivityLogViewModel.swift index d51d4cb6d..57f14dea8 100644 --- a/Shared/ActivityLog/ActivityLogViewModel.swift +++ b/Shared/ActivityLog/ActivityLogViewModel.swift @@ -78,7 +78,7 @@ private extension ActivityLogViewModel { switch owner { case .account(let accountID, _): return .account(accountID: accountID) - case .app, .feedFinder, .feedImageDownloader, .faviconDownloader, .avatarDownloader, .htmlMetadataDownloader: + case .app, .feedFinder, .feedImageDownloader, .faviconDownloader, .avatarDownloader, .htmlMetadataDownloader, .thumbnailDownloader: return .secondary } } diff --git a/Shared/AppDefaults+Shared.swift b/Shared/AppDefaults+Shared.swift deleted file mode 100644 index e4823790d..000000000 --- a/Shared/AppDefaults+Shared.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// AppDefaults+Shared.swift -// NetNewsWire -// -// Created by Brent Simmons on 10/6/26. -// - -import Foundation - -private extension AppDefaults.Key { - static let unreadCountDisplay = "unreadCountDisplay" -} - -extension AppDefaults { - - var unreadCountDisplay: UnreadCountDisplay { - get { - UnreadCountDisplay(rawValue: UserDefaults.standard.integer(forKey: Key.unreadCountDisplay)) ?? .count - } - set { - UserDefaults.standard.set(newValue.rawValue, forKey: Key.unreadCountDisplay) - NotificationCenter.default.post(name: .unreadCountDisplaySettingDidChange, object: self) - } - } -} diff --git a/Shared/AppDefaults.swift b/Shared/AppDefaults.swift new file mode 100644 index 000000000..f40c76a97 --- /dev/null +++ b/Shared/AppDefaults.swift @@ -0,0 +1,323 @@ +// +// AppDefaults.swift +// NetNewsWire +// +// Created by Brent Simmons on 10/22/26. +// + +import Foundation +import Images + +/// Settings common to Mac and iOS. Platform-specific settings are in extensions in AppDefaults+Mac.swift and AppDefaults+iOS.swift. +enum AppDefaults { + + static let defaultThemeName = "Default" + + struct Key { + static let firstRunDate = "firstRunDate" + static let timelineSortDirection = "timelineSortDirection" + static let timelineGroupByFeed = "timelineGroupByFeed" + static let addFeedAccountID = "addFeedAccountID" + static let addFeedFolderName = "addFeedFolderName" + static let addFolderAccountID = "addFolderAccountID" + static let currentThemeName = "currentThemeName" + static let articleContentJavascriptEnabled = "articleContentJavascriptEnabled" + static let unreadCountDisplay = "unreadCountDisplay" + static let timelineThumbnailsDisplay = "timelineThumbnailsDisplay" + static let timelineFeedIconsDisplay = "timelineFeedIconsDisplay" + static let userInterfaceColorPalette = "userInterfaceColorPalette" + static let sidebarShowsIcons = "sidebarShowsIcons" + static let grayscaleIcons = "grayscaleIcons" + static let sidebarTextSize = "sidebarTextSize" + static let showTodayFeed = "showTodayFeed" + static let showUnreadFeed = "showUnreadFeed" + static let showStarredFeed = "showStarredFeed" + static let timelineIconDimension = "timelineIconSize" + static let timelineTextSize = "timelineTextSize" + static let timelineNumberOfLines = "timelineNumberOfLines" + static let timelineShowFullTitles = "timelineShowFullTitles" + static let timelineFadeReadArticles = "timelineFadeReadArticles" + static let timelineFeedNameAndDateAboveTitle = "timelineFeedNameAndDateAboveTitle" + } + + /// Registered by both platforms. Each platform’s registerDefaults adds its own. + static var commonRegisteredDefaults: [String: Any] { + [ + Key.timelineSortDirection: ComparisonResult.orderedDescending.rawValue, + Key.timelineGroupByFeed: false, + Key.currentThemeName: defaultThemeName, + Key.articleContentJavascriptEnabled: true, + Key.timelineThumbnailsDisplay: TimelineThumbnailsDisplay.none.rawValue, + Key.timelineFeedIconsDisplay: TimelineFeedIconsDisplay.automatic.rawValue, + Key.userInterfaceColorPalette: UserInterfaceColorPalette.automatic.rawValue, + Key.sidebarShowsIcons: true, + Key.grayscaleIcons: false, + Key.sidebarTextSize: SidebarTextSize.system.rawValue, + Key.showTodayFeed: true, + Key.showUnreadFeed: true, + Key.showStarredFeed: true, + Key.timelineTextSize: TimelineTextSize.medium.rawValue, + Key.timelineShowFullTitles: false, + Key.timelineFadeReadArticles: false, + Key.timelineFeedNameAndDateAboveTitle: true + ] + } + + static let isDeveloperBuild: Bool = { + if let dev = Bundle.main.object(forInfoDictionaryKey: "DeveloperEntitlements") as? String, dev == "-dev" { + return true + } + return false + }() + + static let isFirstRun: Bool = { + if UserDefaults.standard.object(forKey: Key.firstRunDate) is Date { + return false + } + firstRunDate = Date() + return true + }() + + static var addFeedAccountID: String? { + get { + UserDefaults.standard.string(forKey: Key.addFeedAccountID) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.addFeedAccountID) + } + } + + static var addFeedFolderName: String? { + get { + UserDefaults.standard.string(forKey: Key.addFeedFolderName) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.addFeedFolderName) + } + } + + static var addFolderAccountID: String? { + get { + UserDefaults.standard.string(forKey: Key.addFolderAccountID) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.addFolderAccountID) + } + } + + static var currentThemeName: String? { + get { + UserDefaults.standard.string(forKey: Key.currentThemeName) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.currentThemeName) + } + } + + static var isArticleContentJavascriptEnabled: Bool { + get { + UserDefaults.standard.bool(forKey: Key.articleContentJavascriptEnabled) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.articleContentJavascriptEnabled) + } + } + + static var unreadCountDisplay: UnreadCountDisplay { + get { + UnreadCountDisplay(rawValue: UserDefaults.standard.integer(forKey: Key.unreadCountDisplay)) ?? .count + } + set { + UserDefaults.standard.set(newValue.rawValue, forKey: Key.unreadCountDisplay) + NotificationCenter.default.post(name: .unreadCountDisplaySettingDidChange, object: nil) + } + } + + static var timelineThumbnailsDisplay: TimelineThumbnailsDisplay { + get { + TimelineThumbnailsDisplay(rawValue: UserDefaults.standard.integer(forKey: Key.timelineThumbnailsDisplay)) ?? .none + } + set { + UserDefaults.standard.set(newValue.rawValue, forKey: Key.timelineThumbnailsDisplay) + NotificationCenter.default.post(name: .timelineThumbnailsDisplayDidChange, object: nil) + } + } + + static var timelineFeedIconsDisplay: TimelineFeedIconsDisplay { + get { + TimelineFeedIconsDisplay(rawValue: UserDefaults.standard.integer(forKey: Key.timelineFeedIconsDisplay)) ?? .automatic + } + set { + UserDefaults.standard.set(newValue.rawValue, forKey: Key.timelineFeedIconsDisplay) + NotificationCenter.default.post(name: .timelineFeedIconsDisplayDidChange, object: nil) + } + } + + static var userInterfaceColorPalette: UserInterfaceColorPalette { + get { + UserInterfaceColorPalette(rawValue: UserDefaults.standard.integer(forKey: Key.userInterfaceColorPalette)) ?? .automatic + } + set { + UserDefaults.standard.set(newValue.rawValue, forKey: Key.userInterfaceColorPalette) + NotificationCenter.default.post(name: .userInterfaceColorPaletteDidUpdate, object: nil) + } + } + + static var sidebarShowsIcons: Bool { + get { + UserDefaults.standard.bool(forKey: Key.sidebarShowsIcons) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.sidebarShowsIcons) + NotificationCenter.default.post(name: .sidebarShowsIconsDidChange, object: nil) + } + } + + /// Feed icons, avatars, and sidebar symbols without color. Thumbnails keep their color. + static var grayscaleIcons: Bool { + get { + UserDefaults.standard.bool(forKey: Key.grayscaleIcons) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.grayscaleIcons) + NotificationCenter.default.post(name: .grayscaleIconsDidChange, object: nil) + } + } + + static var sidebarTextSize: SidebarTextSize { + get { + SidebarTextSize(rawValue: UserDefaults.standard.integer(forKey: Key.sidebarTextSize)) ?? .system + } + set { + UserDefaults.standard.set(newValue.rawValue, forKey: Key.sidebarTextSize) + NotificationCenter.default.post(name: .sidebarTextSizeDidChange, object: nil) + } + } + + static var showTodayFeed: Bool { + get { + UserDefaults.standard.bool(forKey: Key.showTodayFeed) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.showTodayFeed) + NotificationCenter.default.post(name: .sidebarSmartFeedsVisibilityDidChange, object: nil) + } + } + + static var showUnreadFeed: Bool { + get { + UserDefaults.standard.bool(forKey: Key.showUnreadFeed) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.showUnreadFeed) + NotificationCenter.default.post(name: .sidebarSmartFeedsVisibilityDidChange, object: nil) + } + } + + static var showStarredFeed: Bool { + get { + UserDefaults.standard.bool(forKey: Key.showStarredFeed) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.showStarredFeed) + NotificationCenter.default.post(name: .sidebarSmartFeedsVisibilityDidChange, object: nil) + } + } + + /// Registered per platform: iOS defaults to medium, Mac to large. + static var timelineIconSize: IconSize { + get { + IconSize(rawValue: UserDefaults.standard.integer(forKey: Key.timelineIconDimension)) ?? .medium + } + set { + UserDefaults.standard.set(newValue.rawValue, forKey: Key.timelineIconDimension) + NotificationCenter.default.post(name: .timelineIconSizeDidChange, object: nil) + } + } + + static var timelineTextSize: TimelineTextSize { + get { + TimelineTextSize(rawValue: UserDefaults.standard.integer(forKey: Key.timelineTextSize)) ?? .medium + } + set { + UserDefaults.standard.set(newValue.rawValue, forKey: Key.timelineTextSize) + NotificationCenter.default.post(name: .timelineTextSizeDidChange, object: nil) + } + } + + /// Lines shared by the title and summary. Registered per platform: iOS defaults to 2, Mac to 3. + static var timelineNumberOfLines: Int { + get { + UserDefaults.standard.integer(forKey: Key.timelineNumberOfLines) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.timelineNumberOfLines) + NotificationCenter.default.post(name: .timelineNumberOfLinesDidChange, object: nil) + } + } + + /// The whole title and no summary, instead of `timelineNumberOfLines` shared by both. + static var timelineShowFullTitles: Bool { + get { + UserDefaults.standard.bool(forKey: Key.timelineShowFullTitles) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.timelineShowFullTitles) + NotificationCenter.default.post(name: .timelineShowFullTitlesDidChange, object: nil) + } + } + + static var timelineFadeReadArticles: Bool { + get { + UserDefaults.standard.bool(forKey: Key.timelineFadeReadArticles) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.timelineFadeReadArticles) + NotificationCenter.default.post(name: .timelineFadeReadArticlesDidChange, object: nil) + } + } + + /// The feed name (or author) and date line goes above the title instead of below the text. + static var timelineFeedNameAndDateAboveTitle: Bool { + get { + UserDefaults.standard.bool(forKey: Key.timelineFeedNameAndDateAboveTitle) + } + set { + UserDefaults.standard.set(newValue, forKey: Key.timelineFeedNameAndDateAboveTitle) + NotificationCenter.default.post(name: .timelineFeedNameAndDateAboveTitleDidChange, object: nil) + } + } +} + +// MARK: - Helpers + +extension AppDefaults { + + static func date(for key: String) -> Date? { + UserDefaults.standard.object(forKey: key) as? Date + } + + static func setDate(for key: String, _ date: Date?) { + UserDefaults.standard.set(date, forKey: key) + } + + static func sortDirection(for key: String) -> ComparisonResult { + let rawInt = UserDefaults.standard.integer(forKey: key) + if rawInt == ComparisonResult.orderedAscending.rawValue { + return .orderedAscending + } + return .orderedDescending + } +} + +private extension AppDefaults { + + static var firstRunDate: Date? { + get { + date(for: Key.firstRunDate) + } + set { + setDate(for: Key.firstRunDate, newValue) + } + } +} diff --git a/Shared/AppDelegate+Shared.swift b/Shared/AppDelegate+Shared.swift index 2fadc7cca..d64fb95a4 100644 --- a/Shared/AppDelegate+Shared.swift +++ b/Shared/AppDelegate+Shared.swift @@ -16,7 +16,7 @@ import RSCore extension AppDelegate { /// Vacuum every database the app owns — the app-level error-log, HTML-metadata, - /// and image-metadata databases, plus each account's databases. + /// and image databases, plus each account's databases. func vacuumAllDatabases() async { await vacuumAndLog(databasePath: AccountManager.shared.errorLogDatabase.databasePath) { await AccountManager.shared.errorLogDatabase.vacuum() @@ -24,8 +24,8 @@ extension AppDelegate { await vacuumAndLog(databasePath: HTMLMetadataDatabase.shared.databasePath) { await HTMLMetadataDatabase.shared.vacuum() } - await vacuumAndLog(databasePath: ImageMetadataDatabase.shared.databasePath) { - await ImageMetadataDatabase.shared.vacuum() + await vacuumAndLog(databasePath: ImageDatabase.shared.databasePath) { + await ImageDatabase.shared.vacuum() } await AccountManager.shared.vacuumAccountDatabases() } diff --git a/Shared/AppNotifications.swift b/Shared/AppNotifications.swift index 82fa76922..647a3c4fe 100644 --- a/Shared/AppNotifications.swift +++ b/Shared/AppNotifications.swift @@ -13,4 +13,12 @@ extension Notification.Name { static let InspectableObjectsDidChange = Notification.Name("TimelineSelectionDidChangeNotification") static let UserDidAddFeed = Notification.Name("UserDidAddFeedNotification") static let WebInspectorEnabledDidChange = Notification.Name("WebInspectorEnabledDidChange") + static let sidebarShowsIconsDidChange = Notification.Name("SidebarShowsIconsDidChangeNotification") + static let grayscaleIconsDidChange = Notification.Name("GrayscaleIconsDidChangeNotification") + static let sidebarSmartFeedsVisibilityDidChange = Notification.Name("SidebarSmartFeedsVisibilityDidChangeNotification") + static let timelineIconSizeDidChange = Notification.Name("TimelineIconSizeDidChangeNotification") + static let timelineNumberOfLinesDidChange = Notification.Name("TimelineNumberOfLinesDidChangeNotification") + static let timelineShowFullTitlesDidChange = Notification.Name("TimelineShowFullTitlesDidChangeNotification") + static let timelineFadeReadArticlesDidChange = Notification.Name("TimelineFadeReadArticlesDidChangeNotification") + static let timelineFeedNameAndDateAboveTitleDidChange = Notification.Name("TimelineFeedNameAndDateAboveTitleDidChangeNotification") } diff --git a/Shared/Article Rendering/ArticleImageSchemeHandler.swift b/Shared/Article Rendering/ArticleImageSchemeHandler.swift new file mode 100644 index 000000000..ad08ce175 --- /dev/null +++ b/Shared/Article Rendering/ArticleImageSchemeHandler.swift @@ -0,0 +1,104 @@ +// +// ArticleImageSchemeHandler.swift +// NetNewsWire +// +// Created by Brent Simmons on 10/27/26. +// + +import Foundation +import CryptoKit +import ImageIO +import UniformTypeIdentifiers +import WebKit +import RSCore +import Images + +/// Serves `ArticleRenderer.articleImageScheme` URLs from the timeline’s copy of the image, +/// downloading it first when needed, so the image is downloaded once. +/// +/// Fails for images ImageIO can’t identify, so the page can fall back to the original URL. +/// +/// Routed URLs are signed with a key made at launch, and unsigned or wrongly signed requests fail. +/// So feed content and script can’t use the scheme to download other images, which would +/// get past content blocking and fill the shared cache. +@MainActor final class ArticleImageSchemeHandler: NSObject, WKURLSchemeHandler { + + /// Never saved, so routed URLs are good only for this run of the app. + private static let signingKey = SymmetricKey(size: .bits256) + /// Percent-encoding leaves only alphanumerics in the encoded image URL, so this can’t appear in it. + private static let signatureSeparator: Character = "?" + + private var runningTaskIDs = Set() // Stopped tasks must not be called again + + func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { + guard let requestURL = urlSchemeTask.request.url, let imageURL = Self.imageURL(requestURL) else { + urlSchemeTask.didFailWithError(URLError(.badURL)) + return + } + + let taskID = ObjectIdentifier(urlSchemeTask) + runningTaskIDs.insert(taskID) + + Task { @MainActor in + var imageData: Data? + var downloadError: Error? + do { + imageData = try await ThumbnailDownloader.shared.fullSizeImageData(url: imageURL, articleTitle: nil) + } catch { + downloadError = error + } + + guard runningTaskIDs.remove(taskID) != nil else { + return + } + guard let imageData, let mimeType = Self.mimeType(imageData) else { + urlSchemeTask.didFailWithError(downloadError ?? URLError(.cannotDecodeContentData)) + return + } + let response = URLResponse(url: requestURL, mimeType: mimeType, expectedContentLength: imageData.count, textEncodingName: nil) + urlSchemeTask.didReceive(response) + urlSchemeTask.didReceive(imageData) + urlSchemeTask.didFinish() + } + } + + func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { + runningTaskIDs.remove(ObjectIdentifier(urlSchemeTask)) + } + + /// The scheme, the percent-encoded image URL, and its signature. + static func routedURLString(_ imageURL: String) -> String? { + guard let encodedURL = imageURL.addingPercentEncoding(withAllowedCharacters: .alphanumerics) else { + return nil + } + return "\(ArticleRenderer.articleImageScheme):\(encodedURL)\(signatureSeparator)\(signature(imageURL))" + } + + /// The image URL, or nil when `requestURL` wasn’t made by `routedURLString` in this run of the app. + static func imageURL(_ requestURL: URL) -> String? { + guard let scheme = requestURL.scheme else { + return nil + } + let routedPart = requestURL.absoluteString.dropFirst(scheme.count + 1) + let parts = routedPart.split(separator: signatureSeparator, maxSplits: 1) + guard parts.count == 2, let imageURL = parts[0].removingPercentEncoding, !imageURL.isEmpty, parts[1] == signature(imageURL) else { + return nil + } + return imageURL + } +} + +private extension ArticleImageSchemeHandler { + + static func signature(_ imageURL: String) -> String { + let authenticationCode = HMAC.authenticationCode(for: Data(imageURL.utf8), using: signingKey) + return Data(authenticationCode).hexadecimalString ?? "" + } + + static func mimeType(_ data: Data) -> String? { + guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil), let typeIdentifier = CGImageSourceGetType(imageSource) else { + return nil + } + return UTType(typeIdentifier as String)?.preferredMIMEType + } +} diff --git a/Shared/Article Rendering/ArticleRenderer+Enclosures.swift b/Shared/Article Rendering/ArticleRenderer+Enclosures.swift new file mode 100644 index 000000000..9057d631a --- /dev/null +++ b/Shared/Article Rendering/ArticleRenderer+Enclosures.swift @@ -0,0 +1,158 @@ +// +// ArticleRenderer+Enclosures.swift +// NetNewsWire +// +// Created by Brent Simmons on 10/23/26. +// + +import Foundation +import RSCore +import RSParser +import Articles + +/// HTML for the `[[enclosures]]` substitution: players for audio and video, and images. +/// Styled with classes, since inline styles get stripped. +extension ArticleRenderer { + + private static let secondsPerMinute = 60 + private static let secondsPerHour = 3600 + /// A WordPress resized copy’s suffix, as in `heron-1024x683.jpg`. + private static let wordPressSizeSuffix = #/-\d+x\d+(?=\.[A-Za-z0-9]+$)/# + + /// Empty when there’s nothing to show. Skips attachments already in the body, including resized copies, + /// since feeds often embed the same image they list as an enclosure. + /// `posterURL` is the poster for video enclosures. + static func enclosuresHTML(attachments: [Attachment]?, body: String, bodyImageIdentities: Set, posterURL: String?) -> String { + let enclosures = (attachments ?? []).filter { !bodyContains($0.url, body: body, bodyImageIdentities: bodyImageIdentities) }.compactMap { enclosureHTML($0, posterURL: posterURL) } + guard !enclosures.isEmpty else { + return "" + } + return "
    \n\(enclosures.joined(separator: "\n"))\n
    " + } + + static func dimensionAttributes(_ attachment: Attachment) -> String { + guard let width = attachment.width, let height = attachment.height else { + return "" + } + return " width=\"\(width)\" height=\"\(height)\"" + } + + /// The `imageIdentity` of each of the body’s images, for spotting resized copies. + static func bodyImageIdentities(_ body: String, baseURL: URL?) -> Set { + Set(HTMLImageParser.significantImageURLStrings(html: body, baseURL: baseURL, maximumCount: Int.max).compactMap(imageIdentity)) + } + + /// True when the body has `url`, a resized copy of the image at `url`, or the YouTube video the image at `url` is a still of. + static func bodyContains(_ url: String, body: String, bodyImageIdentities: Set) -> Bool { + if bodyContainsURL(body, url) { + return true + } + if ArticleRenderingSpecialCases.bodyEmbedsYouTubeVideo(stillImageURL: url, body: body) { + return true + } + guard let identity = imageIdentity(url) else { + return false + } + return bodyImageIdentities.contains(identity) + } + + /// A player or image for one attachment. Nil when it’s not something that can be shown. + static func enclosureHTML(_ attachment: Attachment, posterURL: String?) -> String? { + if let youTubeEmbedURL = ArticleRenderingSpecialCases.youTubeEmbedURL(forAttachmentURL: attachment.url) { + let iframe = "" + return "
    \(iframe)
    " + } + + guard let displayMedium = attachment.displayMedium else { + return nil + } + + let src = attachment.url.escapingSpecialXMLCharacters + let mediaElement: String + let caption: String? + + switch displayMedium { + case .audio: + mediaElement = "" + caption = audioCaption(attachment) + case .video: + var attributes = "controls preload=\"metadata\" playsinline src=\"\(src)\"" + dimensionAttributes(attachment) + if let posterURL, !posterURL.isEmpty { + attributes += " poster=\"\(posterURL.escapingSpecialXMLCharacters)\"" + } + mediaElement = "" + caption = attachment.title + case .image: + mediaElement = "\"\""" + caption = attachment.title + case .document, .executable: + return nil + } + + var html = "
    \(mediaElement)" + if let caption, !caption.isEmpty { + html += "
    \(caption.escapingSpecialXMLCharacters)
    " + } + html += "
    " + return html + } + +} + +private extension ArticleRenderer { + + /// Title (or file name), duration, and size, such as “Episode 311 · 1:54:09 · 54.9 MB”. + static func audioCaption(_ attachment: Attachment) -> String { + var components = [String]() + if let title = attachment.title, !title.isEmpty { + components.append(title) + } else if let fileName = fileName(attachment.url) { + components.append(fileName) + } + if let durationInSeconds = attachment.durationInSeconds { + components.append(durationString(durationInSeconds)) + } + if let sizeInBytes = attachment.sizeInBytes { + components.append(ByteCountFormatter.string(fromByteCount: Int64(sizeInBytes), countStyle: .file)) + } + return components.joined(separator: " · ") + } + + static func durationString(_ durationInSeconds: Int) -> String { + let hours = durationInSeconds / secondsPerHour + let minutes = (durationInSeconds % secondsPerHour) / secondsPerMinute + let seconds = durationInSeconds % secondsPerMinute + if hours > 0 { + return String(format: "%d:%02d:%02d", hours, minutes, seconds) + } + return String(format: "%d:%02d", minutes, seconds) + } + + static func fileName(_ urlString: String) -> String? { + guard let lastPathComponent = URL(string: urlString)?.lastPathComponent, !lastPathComponent.isEmpty, lastPathComponent != "/" else { + return nil + } + return lastPathComponent.removingPercentEncoding ?? lastPathComponent + } + + /// Body HTML escapes `&` in attributes, so check both forms of the URL. + static func bodyContainsURL(_ body: String, _ url: String) -> Bool { + body.contains(url) || body.contains(url.escapingSpecialXMLCharacters) + } + + /// The last two path components, lowercased, without a WordPress size suffix or Engadget size prefix. + /// Two components, since some sites name every image `original.jpg` in its own folder. + /// Ignores the host and query, since resized copies are often served through a resizing service. + static func imageIdentity(_ urlString: String) -> String? { + guard let url = URL(string: urlString) else { + return nil + } + let pathComponents = url.pathComponents.filter { $0 != "/" } + guard let lastPathComponent = pathComponents.last else { + return nil + } + let fileName = ArticleRenderingSpecialCases.removingEngadgetImagePrefix(lastPathComponent, imageURL: urlString).replacing(wordPressSizeSuffix, with: "") + let folderName = pathComponents.dropLast().suffix(1) + return (folderName + [fileName]).joined(separator: "/").lowercased() + } +} diff --git a/Shared/Article Rendering/ArticleRenderer+PrimaryMedia.swift b/Shared/Article Rendering/ArticleRenderer+PrimaryMedia.swift new file mode 100644 index 000000000..5a67e5d7d --- /dev/null +++ b/Shared/Article Rendering/ArticleRenderer+PrimaryMedia.swift @@ -0,0 +1,128 @@ +// +// ArticleRenderer+PrimaryMedia.swift +// NetNewsWire +// +// Created by Brent Simmons on 11/8/26. +// + +import Foundation +import RSCore +import Articles + +/// The article’s main media, for the `[[primary_media]]` substitution: a video, else audio with the article image, else the article image. +extension ArticleRenderer { + + typealias PrimaryMedia = (html: String, attachmentURLs: Set) + + private static let shortPostMaximumBodyLength = 2048 + + /// Untitled and short, as with Mastodon and microblog posts, which put their images after the text. + /// Their images go in the enclosures, not the primary media. + static func isShortUntitledPost(title: String?, body: String) -> Bool { + guard title?.isEmpty ?? true else { + return false + } + return body.count < shortPostMaximumBodyLength + } + + /// Nil when there’s nothing to show. `attachmentURLs` are the attachments (and article image) it shows, for the enclosures to skip. + /// A video’s poster is the article image or thumbnail, so the image isn’t shown separately. + /// When `includesImage` is false, only a video or audio is shown. + static func primaryMedia(imageLink: String?, thumbnailLink: String?, attachments: [Attachment]?, articleTitle: String?, body: String, bodyImageIdentities: Set, includesImage: Bool) -> PrimaryMedia? { + let playableAttachments = (attachments ?? []).filter { !bodyContains($0.url, body: body, bodyImageIdentities: bodyImageIdentities) } + + let posterURL = imageLink ?? thumbnailLink + if let video = playableAttachments.first(where: isVideo), let videoHTML = enclosureHTML(video, posterURL: posterURL) { + var attachmentURLs: Set = [video.url] + if let posterURL { + attachmentURLs.insert(posterURL) + } + return (primaryMediaHTML(videoHTML), attachmentURLs) + } + + var imageHTML = "" + var attachmentURLs = Set() + if includesImage, let image = primaryImage(imageLink: imageLink, thumbnailLink: thumbnailLink, attachments: attachments, body: body, bodyImageIdentities: bodyImageIdentities) { + imageHTML = primaryImageHTML(image, articleTitle: articleTitle) + attachmentURLs.insert(image.url) + } + + if let audio = playableAttachments.first(where: { $0.displayMedium == .audio }), let audioHTML = enclosureHTML(audio, posterURL: nil) { + attachmentURLs.insert(audio.url) + return (primaryMediaHTML(imageHTML + audioHTML), attachmentURLs) + } + + guard !imageHTML.isEmpty else { + return nil + } + return (primaryMediaHTML(imageHTML), attachmentURLs) + } + + /// The article image (JSON Feed `image`, `itunes:image`, or a sync service’s image), else the first image attachment, + /// else the thumbnail (`media:thumbnail`, which Wired uses for its full-size lead image). + /// Nil when the body already has the image, or a resized copy of it at a different URL. + /// An attachment with the same URL supplies the dimensions and title. + static func primaryImage(imageLink: String?, thumbnailLink: String?, attachments: [Attachment]?, body: String, bodyImageIdentities: Set) -> Attachment? { + let attachments = attachments ?? [] + let image: Attachment? + if let imageLink, !imageLink.isEmpty { + image = attachments.first { $0.url == imageLink } ?? imageAttachment(imageLink) + } else if let firstImageAttachment = attachments.first(where: { $0.displayMedium == .image }) { + image = firstImageAttachment + } else if let thumbnailLink, !thumbnailLink.isEmpty { + image = imageAttachment(thumbnailLink) + } else { + image = nil + } + + guard let image, !bodyContains(image.url, body: body, bodyImageIdentities: bodyImageIdentities) else { + return nil + } + return image + } + + /// No caption when the image’s title is the same as the article’s. + static func primaryImageHTML(_ image: Attachment, articleTitle: String?) -> String { + var attributes = "src=\"\(image.url.escapingSpecialXMLCharacters)\"" + var caption = "" + if let title = image.title, !title.isEmpty { + let escapedTitle = title.escapingSpecialXMLCharacters + attributes += " alt=\"\(escapedTitle)\" title=\"\(escapedTitle)\"" + if !isSameTitle(title, articleTitle) { + caption = "
    \(escapedTitle)
    " + } + } else { + attributes += " alt=\"\"" + } + attributes += dimensionAttributes(image) + return "
    \(caption)
    " + } +} + +private extension ArticleRenderer { + + static func primaryMediaHTML(_ html: String) -> String { + "
    \(html)
    " + } + + static func isVideo(_ attachment: Attachment) -> Bool { + attachment.displayMedium == .video || ArticleRenderingSpecialCases.youTubeEmbedURL(forAttachmentURL: attachment.url) != nil + } + + static func imageAttachment(_ url: String) -> Attachment? { + Attachment(url: url, mimeType: nil, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: .image) + } + + static func isSameTitle(_ imageTitle: String, _ articleTitle: String?) -> Bool { + guard let articleTitle else { + return false + } + return collapsingWhitespace(imageTitle).caseInsensitiveCompare(collapsingWhitespace(articleTitle)) == .orderedSame + } + + /// Each run of whitespace, including non-breaking spaces, becomes one space, and the ends are trimmed. + /// Apple Newsroom puts non-breaking spaces in image titles (“MacBook Pro”) but not in article titles. + static func collapsingWhitespace(_ s: String) -> String { + s.split(whereSeparator: \.isWhitespace).joined(separator: " ") + } +} diff --git a/Shared/Article Rendering/ArticleRenderer.swift b/Shared/Article Rendering/ArticleRenderer.swift index 19fe0eee9..5b44bc19c 100644 --- a/Shared/Article Rendering/ArticleRenderer.swift +++ b/Shared/Article Rendering/ArticleRenderer.swift @@ -11,8 +11,10 @@ import Foundation import UIKit #endif import RSCore +import RSParser import Articles import Account +import Images @MainActor struct ArticleRenderer { @@ -31,6 +33,8 @@ import Account } static var imageIconScheme = "nnwImageIcon" + /// Serves an image from the timeline’s copy. The percent-encoded original URL follows the scheme. + static let articleImageScheme = "nnwArticleImage" static var blank = Page(name: "blank") static var page = Page(name: "page") @@ -40,7 +44,13 @@ import Account private let articleTheme: ArticleTheme private let title: String private let body: String - private let baseURL: String? + private let baseURL: URL? + private let routesThumbnailImages: Bool + + private static let primaryMediaKey = "primary_media" + private static let primaryMediaMacro = "[[primary_media]]" + private static let enclosuresKey = "enclosures" + private static let enclosuresMacro = "[[enclosures]]" private static let longDateTimeFormatter: DateFormatter = { let formatter = DateFormatter() @@ -105,49 +115,81 @@ import Account return formatter }() - private init(article: Article?, extractedArticle: ExtractedArticle?, theme: ArticleTheme) { + private init(article: Article?, extractedArticle: ExtractedArticle?, theme: ArticleTheme, routesThumbnailImages: Bool = false) { self.article = article self.extractedArticle = extractedArticle self.articleTheme = theme + self.routesThumbnailImages = routesThumbnailImages self.title = ArticleStringFormatter.sanitizedTitle(article?.title, forHTML: true) ?? "" - // Some feeds embed a full HTML document as the article content — - // render just the body fragment. - // + + var articleBody: String + var baseURL: URL? if let content = extractedArticle?.content { - self.body = ArticleRenderingSpecialCases.extractBodyFragmentIfNeeded(content) - self.baseURL = extractedArticle?.url + articleBody = ArticleRenderingSpecialCases.extractBodyFragmentIfNeeded(content) + if let extractedArticleURL = extractedArticle?.url { + baseURL = URL(string: extractedArticleURL) + } } else { - let articleBody = ArticleRenderingSpecialCases.extractBodyFragmentIfNeeded(article?.body ?? "") - self.body = ArticleRenderingSpecialCases.insertParagraphTagsIfNeeded(articleBody, feedURL: article?.feed?.url, homePageURL: article?.feed?.homePageURL) - self.baseURL = article?.baseURL?.absoluteString + let feedURL = article?.feed?.url + let homePageURL = article?.feed?.homePageURL + + articleBody = ArticleRenderingSpecialCases.extractBodyFragmentIfNeeded(Self.bodyHTML(article)) + articleBody = ArticleRenderingSpecialCases.insertParagraphTagsIfNeeded(articleBody, feedURL: feedURL, homePageURL: homePageURL) + articleBody = ArticleRenderingSpecialCases.removeStrayLineBreaksIfNeeded(articleBody, feedURL: feedURL, homePageURL: homePageURL) + articleBody = ArticleRenderingSpecialCases.enlargeFlickrImagesIfNeeded(articleBody, feedURL: feedURL, attachmentURLs: article?.attachments?.map { $0.url } ?? []) + if article?.account?.type == .freshRSS { + articleBody = ArticleRenderingSpecialCases.desanitizeFreshRSSContent(articleBody) + } + + if let articleBaseURL = article?.baseURL { + baseURL = ArticleRenderingSpecialCases.baseURLForRendering(articleBaseURL) + } } + + self.body = articleBody + self.baseURL = baseURL } // MARK: - API - static func articleHTML(article: Article, extractedArticle: ExtractedArticle? = nil, theme: ArticleTheme) -> Rendering { - let renderer = ArticleRenderer(article: article, extractedArticle: extractedArticle, theme: theme) - return (renderer.articleCSS, renderer.articleHTML, renderer.title, renderer.baseURL ?? "") + /// `routesThumbnailImages` points the thumbnail’s ``s at `articleImageScheme`, which only a web view with `ArticleImageSchemeHandler` can load. + static func articleHTML(article: Article, extractedArticle: ExtractedArticle? = nil, theme: ArticleTheme, routesThumbnailImages: Bool = false) -> Rendering { + let renderer = ArticleRenderer(article: article, extractedArticle: extractedArticle, theme: theme, routesThumbnailImages: routesThumbnailImages) + return (renderer.articleCSS, renderer.articleHTML, renderer.title, renderer.baseURL?.absoluteString ?? "") } static func multipleSelectionHTML(theme: ArticleTheme) -> Rendering { let renderer = ArticleRenderer(article: nil, extractedArticle: nil, theme: theme) - return (renderer.articleCSS, renderer.multipleSelectionHTML, renderer.title, renderer.baseURL ?? "") + return (renderer.articleCSS, renderer.multipleSelectionHTML, renderer.title, renderer.baseURL?.absoluteString ?? "") } static func loadingHTML(theme: ArticleTheme) -> Rendering { let renderer = ArticleRenderer(article: nil, extractedArticle: nil, theme: theme) - return (renderer.articleCSS, renderer.loadingHTML, renderer.title, renderer.baseURL ?? "") + return (renderer.articleCSS, renderer.loadingHTML, renderer.title, renderer.baseURL?.absoluteString ?? "") } static func noSelectionHTML(theme: ArticleTheme) -> Rendering { let renderer = ArticleRenderer(article: nil, extractedArticle: nil, theme: theme) - return (renderer.articleCSS, renderer.noSelectionHTML, renderer.title, renderer.baseURL ?? "") + return (renderer.articleCSS, renderer.noSelectionHTML, renderer.title, renderer.baseURL?.absoluteString ?? "") } static func noContentHTML(theme: ArticleTheme) -> Rendering { let renderer = ArticleRenderer(article: nil, extractedArticle: nil, theme: theme) - return (renderer.articleCSS, renderer.noContentHTML, renderer.title, renderer.baseURL ?? "") + return (renderer.articleCSS, renderer.noContentHTML, renderer.title, renderer.baseURL?.absoluteString ?? "") + } + + /// Full page HTML for a rendering, ready to load into a web view. + static func pageHTML(_ rendering: Rendering, windowScrollY: Int) -> String { + let substitutions = [ + "title": rendering.title, + "baseURL": rendering.baseURL, + "style": rendering.style, + "body": rendering.html, + "windowScrollY": String(windowScrollY) + ] + + let html = try! MacroProcessor.renderedText(withTemplate: page.html, substitutions: substitutions) + return ArticleRenderingSpecialCases.filterHTMLIfNeeded(baseURL: rendering.baseURL, html: html) } } @@ -155,6 +197,17 @@ import Account private extension ArticleRenderer { + /// The article’s body as HTML. Plain text (`contentText`, used when there’s no `contentHTML`) gets converted. + static func bodyHTML(_ article: Article?) -> String { + guard let article else { + return "" + } + if article.contentHTML == nil, let contentText = article.contentText { + return contentText.convertingPlainTextToHTML + } + return article.body ?? "" + } + private var articleHTML: String { return try! MacroProcessor.renderedText(withTemplate: template(), substitutions: articleSubstitutions()) } @@ -223,10 +276,45 @@ private extension ArticleRenderer { d["external_link"] = "" } - d["body"] = body + // Templates without [[primary_media]], and short untitled posts, get the article image in the enclosures. + // The thumbnail is used only for [[primary_media]]. + let bodyImageIdentities = Self.bodyImageIdentities(body, baseURL: baseURL) + var attachments = article.attachments ?? [] + var primaryMediaHTML = "" + var primaryMediaURLs = Set() + let hasPrimaryMedia = template().contains(Self.primaryMediaMacro) + let showsPrimaryImage = hasPrimaryMedia && !Self.isShortUntitledPost(title: article.title, body: body) + if hasPrimaryMedia, let primaryMedia = Self.primaryMedia(imageLink: article.imageLink, thumbnailLink: article.thumbnailLink, attachments: attachments, articleTitle: article.title, body: body, bodyImageIdentities: bodyImageIdentities, includesImage: showsPrimaryImage) { + primaryMediaHTML = primaryMedia.html + primaryMediaURLs = primaryMedia.attachmentURLs + attachments.removeAll { primaryMediaURLs.contains($0.url) } + } + if !showsPrimaryImage, let primaryImage = Self.primaryImage(imageLink: article.imageLink, thumbnailLink: nil, attachments: attachments, body: body, bodyImageIdentities: bodyImageIdentities), !primaryMediaURLs.contains(primaryImage.url), !attachments.contains(primaryImage) { + attachments.insert(primaryImage, at: 0) + } + + // Templates without [[enclosures]] get them at the end of the body. + var enclosures = Self.enclosuresHTML(attachments: attachments, body: body, bodyImageIdentities: bodyImageIdentities, posterURL: article.imageLink ?? article.thumbnailLink) + var body = body + if routesThumbnailImages, let thumbnailMode = AppDefaults.timelineThumbnailsDisplay.thumbnailMode, let thumbnailURL = ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) { + body = Self.routingThumbnailImages(body, thumbnailURL: thumbnailURL, baseURL: baseURL) + enclosures = Self.routingThumbnailImages(enclosures, thumbnailURL: thumbnailURL, baseURL: baseURL) + primaryMediaHTML = Self.routingThumbnailImages(primaryMediaHTML, thumbnailURL: thumbnailURL, baseURL: baseURL) + } + d[Self.primaryMediaKey] = primaryMediaHTML + if template().contains(Self.enclosuresMacro) { + d["body"] = body + d[Self.enclosuresKey] = enclosures + } else if enclosures.isEmpty { + d["body"] = body + } else { + // The wrapper div closes anything the body leaves open, such as an unclosed + //
    diff --git a/Shared/ArticleStyles/ArticleTheme.swift b/Shared/ArticleStyles/ArticleTheme.swift index e9583a95c..e628d8650 100644 --- a/Shared/ArticleStyles/ArticleTheme.swift +++ b/Shared/ArticleStyles/ArticleTheme.swift @@ -16,6 +16,11 @@ struct ArticleTheme: Equatable, Sendable { private static let defaultThemeName = NSLocalizedString("Default", comment: "Default") private static let unknownValue = NSLocalizedString("Unknown", comment: "Unknown Value") + /// Used instead of template.html when present. Older versions of NetNewsWire ignore it, + /// so a theme can use the 7.3 tags here and keep template.html free of them. + private static let template7_3Filename = "template7.3.html" + private static let templateFilename = "template.html" + let url: URL? let template: String? let css: String? @@ -38,11 +43,15 @@ struct ArticleTheme: Equatable, Sendable { return String(describing: info?.version ?? 0) } + var usesGrayscaleIcon: Bool { + info?.grayscaleIcon ?? false + } + private let info: ArticleThemePlist? init() { self.url = nil - self.info = ArticleThemePlist(name: "Article Theme", themeIdentifier: "com.ranchero.netnewswire.theme.article", creatorHomePage: "https://netnewswire.com/", creatorName: "Ranchero Software", version: 1) + self.info = ArticleThemePlist(name: "Article Theme", themeIdentifier: "com.ranchero.netnewswire.theme.article", creatorHomePage: "https://netnewswire.com/", creatorName: "Ranchero Software", version: 1, grayscaleIcon: nil) let corePath = Bundle.main.path(forResource: "core", ofType: "css")! let stylesheetPath = Bundle.main.path(forResource: "stylesheet", ofType: "css")! @@ -70,8 +79,9 @@ struct ArticleTheme: Equatable, Sendable { self.css = nil } - let templateURL = url.appendingPathComponent("template.html") - self.template = Self.stringAtPath(templateURL.path) + let template7_3URL = url.appendingPathComponent(Self.template7_3Filename) + let templateURL = url.appendingPathComponent(Self.templateFilename) + self.template = Self.stringAtPath(template7_3URL.path) ?? Self.stringAtPath(templateURL.path) self.isAppTheme = isAppTheme diff --git a/Shared/ArticleStyles/ArticleThemePlist.swift b/Shared/ArticleStyles/ArticleThemePlist.swift index bac3ac888..aff5b713e 100644 --- a/Shared/ArticleStyles/ArticleThemePlist.swift +++ b/Shared/ArticleStyles/ArticleThemePlist.swift @@ -14,6 +14,7 @@ public struct ArticleThemePlist: Codable, Equatable, Sendable { public let creatorHomePage: String public let creatorName: String public let version: Int + public let grayscaleIcon: Bool? enum CodingKeys: String, CodingKey { case name = "Name" @@ -21,5 +22,6 @@ public struct ArticleThemePlist: Codable, Equatable, Sendable { case creatorHomePage = "CreatorHomePage" case creatorName = "CreatorName" case version = "Version" + case grayscaleIcon = "grayscaleIcon" } } diff --git a/Shared/ArticleStyles/ArticleThemesManager.swift b/Shared/ArticleStyles/ArticleThemesManager.swift index 110a4ccff..8e0f8eab0 100644 --- a/Shared/ArticleStyles/ArticleThemesManager.swift +++ b/Shared/ArticleStyles/ArticleThemesManager.swift @@ -7,7 +7,7 @@ // import Foundation -import os +import Synchronization import RSCore public extension Notification.Name { @@ -52,11 +52,11 @@ final class ArticleThemesManager: NSObject, NSFilePresenter, Sendable { var currentThemeName: String { get { - AppDefaults.shared.currentThemeName ?? AppDefaults.defaultThemeName + AppDefaults.currentThemeName ?? AppDefaults.defaultThemeName } set { if newValue != currentThemeName { - AppDefaults.shared.currentThemeName = newValue + AppDefaults.currentThemeName = newValue updateThemeNames() updateCurrentTheme() } @@ -87,7 +87,7 @@ final class ArticleThemesManager: NSObject, NSFilePresenter, Sendable { var currentTheme = ArticleTheme.defaultTheme var themeNames = [AppDefaults.defaultThemeName] } - private let state = OSAllocatedUnfairLock(initialState: State()) + private let state = Mutex(State()) @MainActor private var didStart = false diff --git a/Shared/Assets.swift b/Shared/Assets.swift index a17c3d4a6..1d0e5c806 100644 --- a/Shared/Assets.swift +++ b/Shared/Assets.swift @@ -42,27 +42,9 @@ struct Assets { nonisolated static var nnwFeedIcon: RSImage { RSImage(named: "nnwFeedIcon")! } static var faviconTemplate: RSImage { RSImage(named: "faviconTemplateImage")! } - static let articleExtractorOff: RSImage = { - if #available(iOS 18, macOS 15, *) { - return RSImage(symbol: "text.page")! - } else { - return RSImage(symbol: "doc.plaintext")! - } - }() - static let articleExtractorOn: RSImage = { - if #available(iOS 18, macOS 15, *) { - return RSImage(symbol: "text.page.fill")! - } else { - return RSImage(symbol: "doc.plaintext.fill")! - } - }() - static let articleExtractorError: RSImage = { - if #available(iOS 18, macOS 15, *) { - return RSImage(symbol: "text.page.slash")! - } else { - return RSImage(symbol: "exclamationmark.triangle")! - } - }() + static let articleExtractorOff: RSImage = RSImage(symbol: "text.page")! + static let articleExtractorOn: RSImage = RSImage(symbol: "text.page.fill")! + static let articleExtractorError: RSImage = RSImage(symbol: "text.page.slash")! static let share = RSImage(symbol: "square.and.arrow.up")! static let folder = RSImage(symbol: "folder")! static let starredFeed = IconImage(starClosed, isSymbol: true, isBackgroundSuppressed: true, preferredColor: Assets.Colors.star) @@ -79,6 +61,8 @@ struct Assets { static let openInBrowser = RSImage(symbol: "safari")! static let preferencesToolbarAccounts = RSImage(symbol: "at")! static let preferencesToolbarGeneral = RSImage(symbol: "gearshape")! + static var preferencesToolbarAppearance: RSImage { RSImage(named: "preferencesToolbarAppearance")! } + static let preferencesToolbarTimeline = RSImage(symbol: "list.bullet.rectangle")! static let preferencesToolbarAdvanced = RSImage(symbol: "gearshape.2")! static let readClosed = RSImage(symbol: "largecircle.fill.circle")! static let readOpen = RSImage(symbol: "circle")! @@ -98,6 +82,7 @@ struct Assets { #else // iOS static var accountLocalPadImage: RSImage { RSImage(named: "accountLocalPad")! } static var accountLocalPhoneImage: RSImage { RSImage(named: "accountLocalPhone")! } + static var timelinePreviewThumbnail: RSImage { RSImage(named: "timelinePreviewThumbnail")! } static let circleClosed = RSImage(symbol: "largecircle.fill.circle")! static let markBelowAsRead = RSImage(symbol: "arrowtriangle.down.circle")! @@ -165,21 +150,25 @@ struct Assets { @MainActor struct Colors { #if os(macOS) static let primaryAccent = RSColor(named: "AccentColor")! - static let timelineSeparator = NSColor(named: "timelineSeparatorColor")! - static let iconLightBackground = NSColor(named: "iconLightBackgroundColor")! - static let iconDarkBackground = NSColor(named: "iconDarkBackgroundColor")! + /// Behind icons that wouldn’t otherwise stand out from the background. + static let iconBackground = NSColor.tertiarySystemFill static let star = RSColor(named: "StarColor")! static let sidebarUnreadCountBackground = RSColor(named: "SidebarUnreadCountBackground")! static let sidebarUnreadCountText = RSColor(named: "SidebarUnreadCountText")! + /// A faint gray, shown until a timeline thumbnail arrives. + static let thumbnailPlaceholder = NSColor.tertiarySystemFill #else // iOS static let primaryAccent = RSColor(named: "primaryAccentColor")! static let secondaryAccent = RSColor(named: "secondaryAccentColor")! static let star = RSColor(named: "starColor")! static let vibrantText = RSColor(named: "vibrantTextColor")! static let controlBackground = RSColor(named: "controlBackgroundColor")! - static let iconBackground = RSColor(named: "iconBackgroundColor")! + /// Behind icons that wouldn’t otherwise stand out from the background. + static let iconBackground = UIColor.quaternarySystemFill static let fullScreenBackground = RSColor(named: "fullScreenBackgroundColor")! static let sectionHeader = RSColor(named: "sectionHeaderColor")! + /// A faint gray, shown until a timeline thumbnail arrives. + static let thumbnailPlaceholder = UIColor.quaternarySystemFill #endif } } diff --git a/Shared/CurrentActivity/CurrentActivityViewModel.swift b/Shared/CurrentActivity/CurrentActivityViewModel.swift index f6afa3d07..34ec51c65 100644 --- a/Shared/CurrentActivity/CurrentActivityViewModel.swift +++ b/Shared/CurrentActivity/CurrentActivityViewModel.swift @@ -94,6 +94,8 @@ struct ActivityDisplayText { return ActivityDisplayText(title: NSLocalizedString("Downloading avatar", comment: "Downloading avatar"), detail: avatarURL) case .downloadHTMLMetadata(let urlString): return ActivityDisplayText(title: NSLocalizedString("Downloading metadata", comment: "Downloading metadata"), detail: urlString) + case .downloadThumbnail(let imageURL): + return ActivityDisplayText(title: NSLocalizedString("Downloading thumbnail", comment: "Downloading thumbnail"), detail: imageURL) default: return ActivityDisplayText(title: activity.kind.simpleDisplayName ?? "", detail: activity.detail) } diff --git a/Shared/Extensions/AddFeedDefaultContainer.swift b/Shared/Extensions/AddFeedDefaultContainer.swift index 43a0cd8f6..95cf29e8a 100644 --- a/Shared/Extensions/AddFeedDefaultContainer.swift +++ b/Shared/Extensions/AddFeedDefaultContainer.swift @@ -13,8 +13,8 @@ import Account static var defaultContainer: Container? { - if let accountID = AppDefaults.shared.addFeedAccountID, let account = AccountManager.shared.activeAccounts.first(where: { $0.accountID == accountID }) { - if let folderName = AppDefaults.shared.addFeedFolderName, let folder = account.existingFolder(withDisplayName: folderName) { + if let accountID = AppDefaults.addFeedAccountID, let account = AccountManager.shared.activeAccounts.first(where: { $0.accountID == accountID }) { + if let folderName = AppDefaults.addFeedFolderName, let folder = account.existingFolder(withDisplayName: folderName) { return folder } else { return substituteContainerIfNeeded(account: account) @@ -28,11 +28,11 @@ import Account } static func saveDefaultContainer(_ container: Container) { - AppDefaults.shared.addFeedAccountID = container.account?.accountID + AppDefaults.addFeedAccountID = container.account?.accountID if let folder = container as? Folder { - AppDefaults.shared.addFeedFolderName = folder.nameForDisplay + AppDefaults.addFeedFolderName = folder.nameForDisplay } else { - AppDefaults.shared.addFeedFolderName = nil + AppDefaults.addFeedFolderName = nil } } diff --git a/Shared/Extensions/ArticleUtilities.swift b/Shared/Extensions/ArticleUtilities.swift index aadb5f2d2..59d2a3c30 100644 --- a/Shared/Extensions/ArticleUtilities.swift +++ b/Shared/Extensions/ArticleUtilities.swift @@ -52,6 +52,10 @@ extension Article { return URL.encodeSpacesIfNeeded(rawImageLink) } + var thumbnailURL: URL? { + URL.encodeSpacesIfNeeded(rawThumbnailLink) + } + var link: String? { // Prefer link from URL, if one can be created, as these are repaired if required. // Provide the raw link if URL creation fails. @@ -70,6 +74,10 @@ extension Article { return imageURL?.absoluteString ?? rawImageLink } + var thumbnailLink: String? { + thumbnailURL?.absoluteString ?? rawThumbnailLink + } + var preferredLink: String? { if let link = link, !link.isEmpty { return link @@ -99,6 +107,33 @@ extension Article { return IconImageCache.shared.imageForArticle(self) } + /// Grayscale when the current theme’s Info.plist sets `grayscaleIcon`. + func articleViewIconImage() -> IconImage? { + guard let iconImage = iconImage() else { + return nil + } + return ArticleThemesManager.shared.currentTheme.usesGrayscaleIcon ? iconImage.grayscaleIconImage : iconImage + } + + /// True when an icon notification is about an icon this article might show: + /// its feed’s icon, or one of its authors’ avatars. + func mightShowIcon(in notification: Notification) -> Bool { + switch notification.name { + case .feedIconImageDidChange: + guard let feed, let notificationFeed = notification.userInfo?[UserInfoKey.feed] as? Feed else { + return false + } + return notificationFeed == feed + case .authorAvatarImageDidChange: + guard let avatarURL = notification.userInfo?[UserInfoKey.url] as? String else { + return false + } + return authors?.contains { $0.avatarURL == avatarURL } ?? false + default: + return false + } + } + func iconImageUrl(feed: Feed) -> URL? { if let image = iconImage() { guard let imageData = image.image.dataRepresentation() else { diff --git a/Shared/Extensions/CacheCleaner.swift b/Shared/Extensions/CacheCleaner.swift index a553e040e..082380eed 100644 --- a/Shared/Extensions/CacheCleaner.swift +++ b/Shared/Extensions/CacheCleaner.swift @@ -14,46 +14,19 @@ struct CacheCleaner { static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "CacheCleaner") - private static let didPurgeImageCachesForResizingKey = "didPurgeImageCachesForResizing-2026-03-30" + private static let didRemoveFoldersReplacedByDownloadedImageCacheKey = "didRemoveFoldersReplacedByDownloadedImageCache-2026-10-27" static func purgeIfNecessary() { - - purgeImageCachesForResizingIfNeeded() - - guard let flushDate = AppDefaults.shared.lastImageCacheFlushDate else { - AppDefaults.shared.lastImageCacheFlushDate = Date() - return - } - - // If the image disk cache hasn't been flushed for 3 days, delete it - if flushDate.addingTimeInterval(3600 * 24 * 3) < Date() { - let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! - let faviconsFolderURL = tempDir.appendingPathComponent("Favicons") - let imagesFolderURL = tempDir.appendingPathComponent("Images") - let feedURLToIconURL = tempDir.appendingPathComponent("FeedURLToIconURLCache.plist") - let homePageToIconURL = tempDir.appendingPathComponent("HomePageToIconURLCache.plist") - let homePagesWithNoIconURL = tempDir.appendingPathComponent("HomePagesWithNoIconURLCache.plist") - - for tempItem in [faviconsFolderURL, imagesFolderURL, feedURLToIconURL, homePageToIconURL, homePagesWithNoIconURL] { - do { - logger.info("Removing cache file: \(tempItem.absoluteString)") - try FileManager.default.removeItem(at: tempItem) - } catch { - logger.error("Could not delete cache file: \(error.localizedDescription)") - } - } - - AppDefaults.shared.lastImageCacheFlushDate = Date() - } + removeFoldersReplacedByDownloadedImageCacheIfNeeded() } } private extension CacheCleaner { - /// One-time purge of image caches so that oversized cached images - /// are replaced with properly resized versions on re-download. - static func purgeImageCachesForResizingIfNeeded() { - guard !UserDefaults.standard.bool(forKey: didPurgeImageCachesForResizingKey) else { + /// One-time removal of the image folders that DownloadedImageCache’s DownloadedImages folder replaces. + /// Off the main thread, since a large old folder can take a while to delete. + static func removeFoldersReplacedByDownloadedImageCacheIfNeeded() { + guard !UserDefaults.standard.bool(forKey: didRemoveFoldersReplacedByDownloadedImageCacheKey) else { return } @@ -64,15 +37,17 @@ private extension CacheCleaner { cacheDir.appendingPathComponent("FeedIcons") ] - for folder in foldersToRemove { - do { - try FileManager.default.removeItem(at: folder) - logger.info("Purged image cache folder: \(folder.lastPathComponent, privacy: .public)") - } catch { - // Folder may not exist yet — that's fine + Task.detached(priority: .utility) { + for folder in foldersToRemove { + do { + try FileManager.default.removeItem(at: folder) + logger.info("Removed image folder replaced by DownloadedImageCache: \(folder.lastPathComponent, privacy: .public)") + } catch { + // Folder may not exist — that's fine + } } - } - UserDefaults.standard.set(true, forKey: didPurgeImageCachesForResizingKey) + UserDefaults.standard.set(true, forKey: didRemoveFoldersReplacedByDownloadedImageCacheKey) + } } } diff --git a/Shared/Extensions/IconImageView.swift b/Shared/Extensions/IconImageView.swift index 59c7f3d3b..bb513ffc1 100644 --- a/Shared/Extensions/IconImageView.swift +++ b/Shared/Extensions/IconImageView.swift @@ -65,8 +65,7 @@ struct IconImageView: View { private var backgroundColor: Color { #if os(macOS) - let nsColor = isDarkMode ? Assets.Colors.iconDarkBackground : Assets.Colors.iconLightBackground - return Color(nsColor: nsColor) + return Color(nsColor: Assets.Colors.iconBackground) #else return Color(Assets.Colors.iconBackground) #endif diff --git a/Shared/Extensions/SmallIconProvider.swift b/Shared/Extensions/SmallIconProvider.swift index 77a9ed3d1..775c0ad86 100644 --- a/Shared/Extensions/SmallIconProvider.swift +++ b/Shared/Extensions/SmallIconProvider.swift @@ -25,10 +25,7 @@ protocol SmallIconProvider { @MainActor extension Feed: SmallIconProvider { var smallIcon: IconImage? { - if let iconImage = FaviconDownloader.shared.favicon(for: self) { - return iconImage - } - return FaviconGenerator.shared.favicon(self) + IconImageCache.shared.iconImage(for: self) } } diff --git a/Shared/IconImageCache.swift b/Shared/IconImageCache.swift index a7c93c16e..2e45237c1 100644 --- a/Shared/IconImageCache.swift +++ b/Shared/IconImageCache.swift @@ -12,24 +12,54 @@ import Articles import RSCore import Images +extension Notification.Name { + /// Posted when the icon `iconImage(for:)` returns for a feed may have changed. userInfo key: `UserInfoKey.feed`. + static let feedIconImageDidChange = Notification.Name("FeedIconImageDidChange") + /// Posted when an author’s avatar loads or changes. userInfo key: `UserInfoKey.url` (the avatar URL). + static let authorAvatarImageDidChange = Notification.Name("AuthorAvatarImageDidChange") +} + +/// The icons the UI shows for feeds, articles, and sidebar items. The UI watches its two notifications, not the downloaders’. @MainActor final class IconImageCache { static var shared = IconImageCache() private var smartFeedIconImageCache = [SidebarItemIdentifier: IconImage]() - private var feedIconImageCache = [SidebarItemIdentifier: IconImage]() - private var faviconImageCache = [SidebarItemIdentifier: IconImage]() + private var lastFoundFeedIconImages = [SidebarItemIdentifier: IconImage]() private var smallIconImageCache = [SidebarItemIdentifier: IconImage]() private var authorIconImageCache = [Author: IconImage]() init() { NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleFeedIconDidChange(_:)), name: .feedIconDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleHomePageIconDidChange(_:)), name: .homePageIconDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleFaviconDidChange(_:)), name: .faviconDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleAvatarDidChange(_:)), name: .avatarDidChange, object: nil) } @objc func handleLowMemory(_ notification: Notification) { emptyCache() } + @objc func handleFeedIconDidChange(_ notification: Notification) { + postFeedIconImageDidChange(notification.userInfo?[FeedIconDownloader.feedsKey] as? Set) + } + + @objc func handleHomePageIconDidChange(_ notification: Notification) { + postFeedIconImageDidChange(notification.userInfo?[HomePageIconDownloader.feedsKey] as? Set) + } + + @objc func handleFaviconDidChange(_ notification: Notification) { + postFeedIconImageDidChange(notification.userInfo?[FaviconDownloader.feedsKey] as? Set) + } + + @objc func handleAvatarDidChange(_ notification: Notification) { + guard let avatarURL = notification.userInfo?[AuthorAvatarDownloader.avatarURLKey] as? String else { + return + } + NotificationCenter.default.post(name: .authorAvatarImageDidChange, object: self, userInfo: [UserInfoKey.url: avatarURL]) + } + func imageFor(_ feedID: SidebarItemIdentifier) -> IconImage? { if let smartFeed = SmartFeedsController.shared.find(by: feedID) { return imageForFeed(smartFeed) @@ -41,16 +71,15 @@ import Images } func imageForFeed(_ sidebarItem: SidebarItem) -> IconImage? { + if let feed = sidebarItem as? Feed { + return iconImage(for: feed) + } guard let sidebarItemID = sidebarItem.sidebarItemID else { return nil } - if let smartFeed = sidebarItem as? PseudoFeed { return imageForSmartFeed(smartFeed, sidebarItemID) } - if let feed = sidebarItem as? Feed, let iconImage = imageForFeed(feed, sidebarItemID) { - return iconImage - } if let smallIconProvider = sidebarItem as? SmallIconProvider { return imageForSmallIconProvider(smallIconProvider, sidebarItemID) } @@ -68,26 +97,25 @@ import Images for author in authors { if let avatarURL = author.avatarURL, !authorsSeen.contains(avatarURL) { authorsSeen.insert(avatarURL) - _ = AuthorAvatarDownloader.shared.image(for: author) + _ = AuthorAvatarDownloader.shared.avatar(for: author) } } } if let feed = article.feed, let feedID = feed.sidebarItemID, !feedsSeen.contains(feedID) { feedsSeen.insert(feedID) - _ = FeedIconDownloader.shared.icon(for: feed) - _ = FaviconDownloader.shared.faviconAsIcon(for: feed) + _ = feedIcon(for: feed) } } } func prefetchImagesForFeeds(_ feeds: [Feed]) { for feed in feeds { - _ = FeedIconDownloader.shared.icon(for: feed) - _ = FaviconDownloader.shared.faviconAsIcon(for: feed) + _ = feedIcon(for: feed) } } + /// Precedence: author avatar, then the feed’s icon. func imageForArticle(_ article: Article) -> IconImage? { if let iconImage = imageForAuthors(article.authors) { return iconImage @@ -95,13 +123,22 @@ import Images guard let feed = article.feed else { return nil } - return imageForFeed(feed) + return iconImage(for: feed) + } + + /// Grayscale when `AppDefaults.grayscaleIcons` is on. + func iconImage(for feed: Feed) -> IconImage { + displayedIconImage(colorIconImage(for: feed)) + } + + /// Grayscale when `AppDefaults.grayscaleIcons` is on. + func displayedIconImage(_ iconImage: IconImage) -> IconImage { + AppDefaults.grayscaleIcons ? iconImage.grayscaleIconImage : iconImage } func emptyCache() { smartFeedIconImageCache.removeAll() - feedIconImageCache.removeAll() - faviconImageCache.removeAll() + lastFoundFeedIconImages.removeAll() smallIconImageCache.removeAll() authorIconImageCache.removeAll() } @@ -118,50 +155,69 @@ private extension IconImageCache { return feed.url.hasPrefix("https://ranchero.com/downloads/netnewswire") } - func imageForSmartFeed(_ smartFeed: PseudoFeed, _ feedID: SidebarItemIdentifier) -> IconImage? { - if let iconImage = smartFeedIconImageCache[feedID] { - return iconImage + /// Precedence: feed icon, home page icon, favicon. + /// Stops at the first source that has an icon or is still loading, so later sources aren’t looked up. + func feedIcon(for feed: Feed) -> IconLookup { + let feedIcon = FeedIconDownloader.shared.feedIcon(for: feed) + guard case .unavailable = feedIcon else { + return feedIcon } - if let iconImage = smartFeed.smallIcon { - smartFeedIconImageCache[feedID] = iconImage - return iconImage + let homePageIcon = HomePageIconDownloader.shared.homePageIcon(for: feed) + guard case .unavailable = homePageIcon else { + return homePageIcon } - return nil + return FaviconDownloader.shared.favicon(for: feed) } - func imageForFeed(_ feed: Feed, _ feedID: SidebarItemIdentifier) -> IconImage? { + /// Precedence: feed icon, home page icon, favicon, generated favicon. + /// + /// While a source is loading, or after the downloaders empty their caches, the icon found last is shown, + /// so an icon doesn’t flash. Without one, the generated favicon is shown. + /// + func colorIconImage(for feed: Feed) -> IconImage { if Self.isNetNewsWireBrandedFeed(feed) { return IconImage.nnwFeedIcon } + let feedID = feed.sidebarItemID + if let iconImage = feedIcon(for: feed).iconImage { + if let feedID { + lastFoundFeedIconImages[feedID] = iconImage + } + return iconImage + } + if let feedID, let iconImage = lastFoundFeedIconImages[feedID] { + return iconImage + } + return FaviconGenerator.shared.favicon(feed) + } - // The downloaders are the source of truth — consult them ahead of the local - // dictionaries so a newly arrived icon replaces a stale one. The dictionaries - // keep the last known icons across the downloaders’ low-memory and background flushes. - // - if let iconImage = FeedIconDownloader.shared.cachedIcon(for: feed) { - feedIconImageCache[feedID] = iconImage - return iconImage + func postFeedIconImageDidChange(_ feeds: Set?) { + guard let feeds else { + return } - if let iconImage = feedIconImageCache[feedID] { - return iconImage + for feed in feeds { + NotificationCenter.default.post(name: .feedIconImageDidChange, object: self, userInfo: [UserInfoKey.feed: feed]) } - if let faviconImage = FaviconDownloader.shared.cachedFaviconAsIcon(for: feed) { - faviconImageCache[feedID] = faviconImage - return faviconImage + } + + func imageForSmartFeed(_ smartFeed: PseudoFeed, _ feedID: SidebarItemIdentifier) -> IconImage? { + if let iconImage = smartFeedIconImageCache[feedID] { + return displayedIconImage(iconImage) } - if let faviconImage = faviconImageCache[feedID] { - return faviconImage + if let iconImage = smartFeed.smallIcon { + smartFeedIconImageCache[feedID] = iconImage + return displayedIconImage(iconImage) } return nil } func imageForSmallIconProvider(_ provider: SmallIconProvider, _ feedID: SidebarItemIdentifier) -> IconImage? { if let iconImage = smallIconImageCache[feedID] { - return iconImage + return displayedIconImage(iconImage) } if let iconImage = provider.smallIcon { smallIconImageCache[feedID] = iconImage - return iconImage + return displayedIconImage(iconImage) } return nil } @@ -174,13 +230,13 @@ private extension IconImageCache { } func imageForAuthor(_ author: Author) -> IconImage? { - if let iconImage = authorIconImageCache[author] { - return iconImage - } - if let iconImage = AuthorAvatarDownloader.shared.cachedImage(for: author) { + if let iconImage = AuthorAvatarDownloader.shared.avatar(for: author).iconImage { authorIconImageCache[author] = iconImage - return iconImage + return displayedIconImage(iconImage) } - return nil + guard let iconImage = authorIconImageCache[author] else { + return nil + } + return displayedIconImage(iconImage) } } diff --git a/Shared/Localizable.xcstrings b/Shared/Localizable.xcstrings index 033079b98..566273dfb 100644 --- a/Shared/Localizable.xcstrings +++ b/Shared/Localizable.xcstrings @@ -45,27 +45,8 @@ "%lld months" : { "comment" : "Dinosaur staleness threshold in months" }, - "Are you sure you want to delete the account “%@”? This cannot be undone." : { - "comment" : "Delete account alert message", - "localizations" : { - "es" : { - "stringUnit" : { - "state" : "translated", - "value" : "¿Seguro que quieres eliminar la cuenta «%@»? Esta acción no se puede deshacer." - } - } - } - }, - "Delete “%@”?" : { - "comment" : "Delete account alert title", - "localizations" : { - "es" : { - "stringUnit" : { - "state" : "translated", - "value" : "¿Eliminar «%@»?" - } - } - } + "^[%lld folder](inflect: true), ^[%lld feed](inflect: true)" : { + "comment" : "Status bar: number of folders and feeds" }, "🦖 Dinosaurs" : { "comment" : "The title of the Dinosaurs screen.", @@ -116,6 +97,9 @@ } } }, + "Actions" : { + "comment" : "Status bar gear menu accessibility label" + }, "Active" : { "localizations" : { "es" : { @@ -200,12 +184,18 @@ "Already added" : { "comment" : "Feed finder" }, + "Always" : { + "comment" : "Always" + }, "Always Use Reader View" : { "comment" : "Always Use Reader View" }, "API URL: https://fresh.rss.net/api/greader.php" : { "comment" : "FreshRSS API Helper" }, + "Appearance" : { + "comment" : "Preferences" + }, "Are you sure you want to delete %d feeds?" : { "comment" : "Delete feeds alert message" }, @@ -218,6 +208,17 @@ "Are you sure you want to delete the %d selected items?" : { "comment" : "Items delete text" }, + "Are you sure you want to delete the account “%@”? This cannot be undone." : { + "comment" : "Delete account alert message", + "localizations" : { + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "¿Seguro que quieres eliminar la cuenta «%@»? Esta acción no se puede deshacer." + } + } + } + }, "Are you sure you want to delete the feed “%@”?" : { "comment" : "Delete feed alert message" }, @@ -371,6 +372,9 @@ } } }, + "Copy" : { + "comment" : "Command" + }, "Copy Article URL" : { "comment" : "Command" }, @@ -449,6 +453,17 @@ } } }, + "Delete “%@”?" : { + "comment" : "Delete account alert title", + "localizations" : { + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "¿Eliminar «%@»?" + } + } + } + }, "Delete Feed" : { "comment" : "Delete Feed" }, @@ -523,6 +538,9 @@ "Downloading metadata" : { "comment" : "Downloading metadata" }, + "Downloading thumbnail" : { + "comment" : "Downloading thumbnail" + }, "Duplicate Theme" : { "comment" : "Duplicate Theme" }, @@ -583,6 +601,9 @@ "Extra Large" : { "comment" : "X-Large" }, + "Fade Read Articles" : { + "comment" : "Timeline Layout: switch that fades read articles in the timeline" + }, "Failed" : { "comment" : "Failed" }, @@ -600,9 +621,18 @@ } } }, + "Feed Icon Size" : { + "comment" : "Feed Icon Size" + }, + "Feed Icons" : { + "comment" : "Feed Icons" + }, "Feed Inspector" : { "comment" : "Feed Inspector window title" }, + "Feed Name and Date Above Title" : { + "comment" : "Timeline Layout: switch that shows the feed name and date above the title in the timeline" + }, "Feeds" : { "comment" : "Feeds" }, @@ -642,9 +672,15 @@ "Folders" : { "comment" : "Folders" }, + "Folders, smart feeds, and authors with avatars" : { + "comment" : "Feed Icons setting: explains when Automatic shows feed icons" + }, "from cache" : { "comment" : "Activity log — appended when a download was served from cache instead of the network" }, + "Full Title, No Preview" : { + "comment" : "Timeline Layout: Rows choice that shows the whole title, without the article preview, in the timeline" + }, "General" : { "comment" : "Preferences", "localizations" : { @@ -695,6 +731,15 @@ "Hide Read Feeds" : { "comment" : "Command" }, + "Hide Sidebar" : { + "comment" : "Command" + }, + "Hide Status Bar" : { + "comment" : "Command" + }, + "Hide Theme Menu in Status Bar" : { + "comment" : "Command" + }, "How to Optimize iCloud Syncing" : { "comment" : "Help link" }, @@ -718,12 +763,6 @@ "iCloud Storage Stats" : { "comment" : "iCloud Storage Stats window title" }, - "Icon Preview" : { - "comment" : "Icon Preview" - }, - "Icon Size" : { - "comment" : "Icon Size" - }, "Import Failed" : { "comment" : "Import Failed" }, @@ -774,6 +813,9 @@ "Light" : { "comment" : "Light" }, + "Lines" : { + "comment" : "Lines" + }, "Link:" : { "comment" : "Link" }, @@ -865,6 +907,18 @@ "Multiple" : { "comment" : "Multiple" }, + "Multiple feeds" : { + "comment" : "Status bar gear menu: header for a selection of several feeds" + }, + "Multiple folders" : { + "comment" : "Status bar gear menu: header for a selection of several folders" + }, + "Multiple selection" : { + "comment" : "Status bar gear menu: header for a selection of different kinds of items" + }, + "Multiple smart feeds" : { + "comment" : "Status bar gear menu: header for a selection of several smart feeds" + }, "Name" : { "comment" : "Name field placeholder" }, @@ -891,6 +945,9 @@ "Network error. Try again later." : { "comment" : "Credentials Error" }, + "Never" : { + "comment" : "Never" + }, "New Article Notifications" : { "comment" : "New Article Notifications" }, @@ -898,13 +955,13 @@ "comment" : "Command" }, "New Feed…" : { - "comment" : "New Feed" + "comment" : "Command" }, "New Folder" : { "comment" : "Command" }, "New Folder…" : { - "comment" : "New Folder" + "comment" : "Command" }, "Newest Article on Top" : { "comment" : "Sort direction", @@ -938,12 +995,15 @@ "No Errors Logged" : { "comment" : "Error log empty state" }, - "No Icon Preview" : { - "comment" : "No Icon Preview" - }, "No results" : { "comment" : "No results" }, + "None" : { + "comment" : "None" + }, + "Not updated yet" : { + "comment" : "Status bar: no refresh has completed yet" + }, "Notifications" : { "comment" : "Notifications" }, @@ -957,9 +1017,6 @@ "Notifications need to be enabled in the Settings app." : { "comment" : "Notifications need to be enabled in the Settings app." }, - "Number of Lines" : { - "comment" : "Number of Lines" - }, "OK" : { "comment" : "OK button" }, @@ -1019,6 +1076,18 @@ "Pending" : { "comment" : "Pending" }, + "Preview" : { + "comment" : "Preview" + }, + "Preview with Feed Icon" : { + "comment" : "Timeline Layout: header for the preview that shows a feed icon" + }, + "Preview with Feed Icon and Thumbnail" : { + "comment" : "Timeline Layout: header for the preview that shows a feed icon and a thumbnail" + }, + "Preview with Thumbnail" : { + "comment" : "Timeline Layout: header for the preview that shows a thumbnail" + }, "Previous Article" : { "comment" : "Previous Article" }, @@ -1067,6 +1136,9 @@ "Return to Previous Scan Results" : { "comment" : "Return to previous scan results button" }, + "Rows" : { + "comment" : "Rows" + }, "Running" : { "comment" : "Running" }, @@ -1185,12 +1257,24 @@ "Show Reader View" : { "comment" : "Show Reader View" }, + "Show Sidebar" : { + "comment" : "Command" + }, + "Show Status Bar" : { + "comment" : "Command" + }, + "Show Theme Menu in Status Bar" : { + "comment" : "Command" + }, "Show Website" : { "comment" : "Show Website" }, "Shows current activity" : { "comment" : "Current Activity accessibility hint" }, + "Shows the whole title, up to %d lines." : { + "comment" : "Timeline Layout: explains the Full Title, No Preview choice" + }, "Sign in to your BazQux account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have a BazQux account?" : { "comment" : "BazQux" }, @@ -1248,6 +1332,9 @@ "Starred" : { "comment" : "Starred" }, + "Status Bar" : { + "comment" : "Main window status bar accessibility label" + }, "Status Records" : { "comment" : "Status records section header" }, @@ -1277,6 +1364,9 @@ } } }, + "System" : { + "comment" : "System" + }, "System Default (%@)" : { "comment" : "Default browser item title format", "localizations" : { @@ -1357,6 +1447,9 @@ "This will delete:" : { "comment" : "Clean up confirmation prefix" }, + "Thumbnails" : { + "comment" : "Thumbnails" + }, "Timeline" : { "comment" : "Timeline" }, @@ -1414,6 +1507,9 @@ "Title (Optional)" : { "comment" : "Feed title placeholder" }, + "Title and Preview" : { + "comment" : "Title and Preview" + }, "To add an account to NetNewsWire,\nclick its icon above.\n\nOr click the + button in the lower left." : { "comment" : "Add Account Explainer", "localizations" : { diff --git a/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift b/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift index 9ea8fbbc5..308d8d7a6 100644 --- a/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift +++ b/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift @@ -9,6 +9,7 @@ import Foundation import RSCore import os +import Synchronization import Account final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter, Sendable { @@ -36,7 +37,7 @@ final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter, Sendable { operationQueue } - private let didStart = OSAllocatedUnfairLock(initialState: false) + private let didStart = Mutex(false) func start() { let alreadyStarted = didStart.withLock { didStart -> Bool in diff --git a/Shared/ShareExtension/ShareDefaultContainer.swift b/Shared/ShareExtension/ShareDefaultContainer.swift index 3965b3f60..06817ce9c 100644 --- a/Shared/ShareExtension/ShareDefaultContainer.swift +++ b/Shared/ShareExtension/ShareDefaultContainer.swift @@ -10,10 +10,13 @@ import Foundation @MainActor struct ShareDefaultContainer { + private static let addFeedAccountIDKey = "addFeedAccountID" + private static let addFeedFolderNameKey = "addFeedFolderName" + static func defaultContainer(containers: ExtensionContainers) -> ExtensionContainer? { - if let accountID = AppDefaults.shared.addFeedAccountID, let account = containers.accounts.first(where: { $0.accountID == accountID }) { - if let folderName = AppDefaults.shared.addFeedFolderName, let folder = account.folders.first(where: { $0.name == folderName }) { + if let accountID = UserDefaults.standard.string(forKey: addFeedAccountIDKey), let account = containers.accounts.first(where: { $0.accountID == accountID }) { + if let folderName = UserDefaults.standard.string(forKey: addFeedFolderNameKey), let folder = account.folders.first(where: { $0.name == folderName }) { return folder } else { return substituteContainerIfNeeded(account: account) @@ -27,11 +30,11 @@ import Foundation } static func saveDefaultContainer(_ container: ExtensionContainer) { - AppDefaults.shared.addFeedAccountID = container.accountID + UserDefaults.standard.set(container.accountID, forKey: addFeedAccountIDKey) if let folder = container as? ExtensionFolder { - AppDefaults.shared.addFeedFolderName = folder.name + UserDefaults.standard.set(folder.name, forKey: addFeedFolderNameKey) } else { - AppDefaults.shared.addFeedFolderName = nil + UserDefaults.standard.removeObject(forKey: addFeedFolderNameKey) } } diff --git a/Shared/SidebarTextSize.swift b/Shared/SidebarTextSize.swift new file mode 100644 index 000000000..759da3495 --- /dev/null +++ b/Shared/SidebarTextSize.swift @@ -0,0 +1,39 @@ +// +// SidebarTextSize.swift +// NetNewsWire +// +// Created by Brent Simmons on 11/6/26. +// + +import Foundation + +extension Notification.Name { + static let sidebarTextSizeDidChange = Notification.Name("SidebarTextSizeDidChangeNotification") +} + +/// Text size in the sidebar. +enum SidebarTextSize: Int, CaseIterable, CustomStringConvertible { + case system = 0 + case small = 1 + case medium = 2 + case large = 3 + case extraLarge = 4 + case extraExtraLarge = 5 + + var description: String { + switch self { + case .system: + NSLocalizedString("System", comment: "System") + case .small: + NSLocalizedString("Small", comment: "Small") + case .medium: + NSLocalizedString("Medium", comment: "Medium") + case .large: + NSLocalizedString("Large", comment: "Large") + case .extraLarge: + NSLocalizedString("Extra Large", comment: "X-Large") + case .extraExtraLarge: + NSLocalizedString("Extra Extra Large", comment: "XX-Large") + } + } +} diff --git a/Shared/SmartFeeds/SmartFeedsController.swift b/Shared/SmartFeeds/SmartFeedsController.swift index da9902ee3..149ecee24 100644 --- a/Shared/SmartFeeds/SmartFeedsController.swift +++ b/Shared/SmartFeeds/SmartFeedsController.swift @@ -21,6 +21,25 @@ import Account let unreadFeed = UnreadFeed() let starredFeed = SmartFeed(delegate: StarredFeedDelegate()) + /// The smart feeds shown in the sidebar. All smart feeds exist regardless. + var shownSmartFeeds: [SidebarItem] { + var feeds = [SidebarItem]() + if AppDefaults.showTodayFeed { + feeds.append(todayFeed) + } + if AppDefaults.showUnreadFeed { + feeds.append(unreadFeed) + } + if AppDefaults.showStarredFeed { + feeds.append(starredFeed) + } + return feeds + } + + func isShown(_ smartFeed: SidebarItem) -> Bool { + shownSmartFeeds.contains { $0.sidebarItemID == smartFeed.sidebarItemID } + } + private init() { self.smartFeeds = [todayFeed, unreadFeed, starredFeed] } diff --git a/Shared/Timeline/FetchRequestOperation.swift b/Shared/Timeline/FetchRequestOperation.swift index 0de7a9d07..b644bdf28 100644 --- a/Shared/Timeline/FetchRequestOperation.swift +++ b/Shared/Timeline/FetchRequestOperation.swift @@ -13,6 +13,7 @@ import RSDatabase import Account import Articles import ErrorLog +import Images // Main thread only. // Runs an asynchronous fetch. @@ -33,12 +34,14 @@ typealias FetchRequestOperationResultBlock = (Set
    , FetchRequestOperatio var isCanceled = false var isFinished = false private let fetchers: [ArticleFetcher] + private let findsThumbnailURLs: Bool - init(id: Int, readFilterEnabledTable: [SidebarItemIdentifier: Bool], fetchers: [ArticleFetcher], resultBlock: @escaping FetchRequestOperationResultBlock) { + init(id: Int, readFilterEnabledTable: [SidebarItemIdentifier: Bool], fetchers: [ArticleFetcher], findsThumbnailURLs: Bool, resultBlock: @escaping FetchRequestOperationResultBlock) { precondition(Thread.isMainThread) self.id = id self.readFilterEnabledTable = readFilterEnabledTable self.fetchers = fetchers + self.findsThumbnailURLs = findsThumbnailURLs self.resultBlock = resultBlock } @@ -74,7 +77,7 @@ typealias FetchRequestOperationResultBlock = (Set
    , FetchRequestOperatio var fetchersReturned = 0 var fetchedArticles = Set
    () - @MainActor func process(_ articles: Set
    ) { + @MainActor func process(_ articles: Set
    ) async { precondition(Thread.isMainThread) guard !self.isCanceled else { callCompletionIfNeeded() @@ -86,6 +89,13 @@ typealias FetchRequestOperationResultBlock = (Set
    , FetchRequestOperatio fetchedArticles.formUnion(articles) fetchersReturned += 1 if fetchersReturned == numberOfFetchers { + if findsThumbnailURLs { + await ArticleThumbnailFinder.shared.findThumbnailURLs(for: fetchedArticles) + guard !self.isCanceled else { + callCompletionIfNeeded() + return + } + } self.isFinished = true self.resultBlock(fetchedArticles, self) callCompletionIfNeeded() @@ -101,7 +111,7 @@ typealias FetchRequestOperationResultBlock = (Set
    , FetchRequestOperatio articles = await fetcher.fetchArticlesAsync() } - process(articles) + await process(articles) } // Belt-and-suspenders: ensure the queue never deadlocks even if @@ -121,12 +131,14 @@ typealias FetchRequestOperationResultBlock = (Set
    , FetchRequestOperatio var isCanceled = false var isFinished = false private let fetchers: [ArticleFetcher] + private let findsThumbnailURLs: Bool - init(id: Int, hidingReadArticlesState: HidingReadArticlesState, fetchers: [ArticleFetcher], resultBlock: @escaping FetchRequestOperationResultBlock) { + init(id: Int, hidingReadArticlesState: HidingReadArticlesState, fetchers: [ArticleFetcher], findsThumbnailURLs: Bool, resultBlock: @escaping FetchRequestOperationResultBlock) { precondition(Thread.isMainThread) self.id = id self.hidingReadArticlesState = hidingReadArticlesState self.fetchers = fetchers + self.findsThumbnailURLs = findsThumbnailURLs self.resultBlock = resultBlock } @@ -162,7 +174,7 @@ typealias FetchRequestOperationResultBlock = (Set
    , FetchRequestOperatio var fetchersReturned = 0 var fetchedArticles = Set
    () - @MainActor func process(_ articles: Set
    ) { + @MainActor func process(_ articles: Set
    ) async { precondition(Thread.isMainThread) guard !self.isCanceled else { callCompletionIfNeeded() @@ -174,6 +186,13 @@ typealias FetchRequestOperationResultBlock = (Set
    , FetchRequestOperatio fetchedArticles.formUnion(articles) fetchersReturned += 1 if fetchersReturned == numberOfFetchers { + if findsThumbnailURLs { + await ArticleThumbnailFinder.shared.findThumbnailURLs(for: fetchedArticles) + guard !self.isCanceled else { + callCompletionIfNeeded() + return + } + } self.isFinished = true self.resultBlock(fetchedArticles, self) callCompletionIfNeeded() @@ -194,7 +213,7 @@ typealias FetchRequestOperationResultBlock = (Set
    , FetchRequestOperatio } else { articles = await fetcher.fetchArticlesAsync() } - process(articles) + await process(articles) } // Ensure the queue never deadlocks even if diff --git a/Shared/TimelineFeedIconsDisplay.swift b/Shared/TimelineFeedIconsDisplay.swift new file mode 100644 index 000000000..1f106a6c9 --- /dev/null +++ b/Shared/TimelineFeedIconsDisplay.swift @@ -0,0 +1,40 @@ +// +// TimelineFeedIconsDisplay.swift +// NetNewsWire +// +// Created by Brent Simmons on 10/26/26. +// + +import Foundation + +extension Notification.Name { + static let timelineFeedIconsDisplayDidChange = Notification.Name("TimelineFeedIconsDisplayDidChangeNotification") +} + +/// When the timeline shows feed icons. +enum TimelineFeedIconsDisplay: Int, CaseIterable, CustomStringConvertible { + case automatic = 0 // Folders, smart feeds, and single feeds whose articles have author avatars + case always = 1 + case never = 2 + + var description: String { + switch self { + case .automatic: + NSLocalizedString("Automatic", comment: "Automatic") + case .always: + NSLocalizedString("Always", comment: "Always") + case .never: + NSLocalizedString("Never", comment: "Never") + } + } + + /// Explains a choice whose description doesn’t say what it does. + var subtitle: String? { + switch self { + case .automatic: + NSLocalizedString("Folders, smart feeds, and authors with avatars", comment: "Feed Icons setting: explains when Automatic shows feed icons") + case .always, .never: + nil + } + } +} diff --git a/Shared/TimelineTextSize.swift b/Shared/TimelineTextSize.swift new file mode 100644 index 000000000..9c0e381d6 --- /dev/null +++ b/Shared/TimelineTextSize.swift @@ -0,0 +1,36 @@ +// +// TimelineTextSize.swift +// NetNewsWire +// +// Created by Brent Simmons on 11/7/26. +// + +import Foundation + +extension Notification.Name { + static let timelineTextSizeDidChange = Notification.Name("TimelineTextSizeDidChangeNotification") +} + +/// Text size in the timeline. +enum TimelineTextSize: Int, CaseIterable, CustomStringConvertible { + case small = 1 + case medium = 2 + case large = 3 + case extraLarge = 4 + case extraExtraLarge = 5 + + var description: String { + switch self { + case .small: + NSLocalizedString("Small", comment: "Small") + case .medium: + NSLocalizedString("Medium", comment: "Medium") + case .large: + NSLocalizedString("Large", comment: "Large") + case .extraLarge: + NSLocalizedString("Extra Large", comment: "X-Large") + case .extraExtraLarge: + NSLocalizedString("Extra Extra Large", comment: "XX-Large") + } + } +} diff --git a/Shared/TimelineThumbnailsDisplay.swift b/Shared/TimelineThumbnailsDisplay.swift new file mode 100644 index 000000000..e55081ebc --- /dev/null +++ b/Shared/TimelineThumbnailsDisplay.swift @@ -0,0 +1,43 @@ +// +// TimelineThumbnailsDisplay.swift +// NetNewsWire +// +// Created by Brent Simmons on 10/26/26. +// + +import Foundation +import Images + +extension Notification.Name { + static let timelineThumbnailsDisplayDidChange = Notification.Name("TimelineThumbnailsDisplayDidChangeNotification") +} + +/// How article thumbnails are shown in the timeline. +enum TimelineThumbnailsDisplay: Int, CaseIterable, CustomStringConvertible { + case none = 0 // Also what integer(forKey:) returns for a missing value + case small = 1 // To the right of the text + case large = 2 // Below the text, spanning the cell + + var description: String { + switch self { + case .small: + NSLocalizedString("Small", comment: "Small") + case .large: + NSLocalizedString("Large", comment: "Large") + case .none: + NSLocalizedString("None", comment: "None") + } + } + + /// Nil when the timeline doesn’t show thumbnails. + var thumbnailMode: ThumbnailMode? { + switch self { + case .small: + .small + case .large: + .large + case .none: + nil + } + } +} diff --git a/Shared/Timer/AccountRefreshTimer.swift b/Shared/Timer/AccountRefreshTimer.swift index 457146d6f..22c189341 100644 --- a/Shared/Timer/AccountRefreshTimer.swift +++ b/Shared/Timer/AccountRefreshTimer.swift @@ -23,7 +23,7 @@ import ActivityLog func fireOldTimer() { if let timer = internalTimer { if timer.fireDate < Date() { - if AppDefaults.shared.refreshInterval != .manually { + if AppDefaults.refreshInterval != .manually { timedRefresh(nil) } } @@ -63,7 +63,7 @@ import ActivityLog return } - let refreshInterval = AppDefaults.shared.refreshInterval + let refreshInterval = AppDefaults.refreshInterval if refreshInterval == .manually { invalidate() return diff --git a/Shared/Tree/SidebarTreeControllerDelegate.swift b/Shared/Tree/SidebarTreeControllerDelegate.swift index 249a6f79a..c47ff0a69 100644 --- a/Shared/Tree/SidebarTreeControllerDelegate.swift +++ b/Shared/Tree/SidebarTreeControllerDelegate.swift @@ -43,10 +43,12 @@ private extension SidebarTreeControllerDelegate { func childNodesForRootNode(_ rootNode: Node) -> [Node]? { var topLevelNodes = [Node]() - let smartFeedsNode = rootNode.existingOrNewChildNode(with: SmartFeedsController.shared) - smartFeedsNode.canHaveChildNodes = true - smartFeedsNode.isGroupItem = true - topLevelNodes.append(smartFeedsNode) + if !SmartFeedsController.shared.shownSmartFeeds.isEmpty { + let smartFeedsNode = rootNode.existingOrNewChildNode(with: SmartFeedsController.shared) + smartFeedsNode.canHaveChildNodes = true + smartFeedsNode.isGroupItem = true + topLevelNodes.append(smartFeedsNode) + } topLevelNodes.append(contentsOf: sortedAccountNodes(rootNode)) @@ -54,7 +56,7 @@ private extension SidebarTreeControllerDelegate { } func childNodesForSmartFeeds(_ parentNode: Node) -> [Node] { - return SmartFeedsController.shared.smartFeeds.compactMap { (feed) -> Node? in + return SmartFeedsController.shared.shownSmartFeeds.compactMap { (feed) -> Node? in // All Smart Feeds should remain visible despite the Hide Read Feeds setting return parentNode.existingOrNewChildNode(with: feed as AnyObject) } diff --git a/Shared/UserInterfaceColorPalette.swift b/Shared/UserInterfaceColorPalette.swift new file mode 100644 index 000000000..736e20614 --- /dev/null +++ b/Shared/UserInterfaceColorPalette.swift @@ -0,0 +1,30 @@ +// +// UserInterfaceColorPalette.swift +// NetNewsWire +// +// Created by Brent Simmons on 11/6/26. +// + +import Foundation + +extension Notification.Name { + static let userInterfaceColorPaletteDidUpdate = Notification.Name("UserInterfaceColorPaletteDidUpdateNotification") +} + +/// Whether the app follows the system appearance or is forced to light or dark. +enum UserInterfaceColorPalette: Int, CustomStringConvertible, CaseIterable { + case automatic = 0 // Follows the system + case light = 1 + case dark = 2 + + var description: String { + switch self { + case .automatic: + NSLocalizedString("Automatic", comment: "Automatic") + case .light: + NSLocalizedString("Light", comment: "Light") + case .dark: + NSLocalizedString("Dark", comment: "Dark") + } + } +} diff --git a/Shared/Widget/WidgetDataEncoder.swift b/Shared/Widget/WidgetDataEncoder.swift index f48ae575d..f62828ce0 100644 --- a/Shared/Widget/WidgetDataEncoder.swift +++ b/Shared/Widget/WidgetDataEncoder.swift @@ -161,7 +161,7 @@ import Account starredArticles: starredArticles, todayArticles: todayArticles, lastUpdateTime: Date.now, - unreadCountDisplay: AppDefaults.shared.unreadCountDisplay) + unreadCountDisplay: AppDefaults.unreadCountDisplay) return latestData } diff --git a/Technotes/ReleaseNotes-Mac.markdown b/Technotes/ReleaseNotes-Mac.markdown index 8eb9cd8b5..5d66f2ebe 100644 --- a/Technotes/ReleaseNotes-Mac.markdown +++ b/Technotes/ReleaseNotes-Mac.markdown @@ -1,5 +1,139 @@ # Mac Release Notes +### 7.3b7 7234 9 Nov 2026 - branch: main tag: mac-7.3b7 + +Make image cache eviction less aggressive, which should fix a loop where images get evicted, re-cached, evicted, re-cached, etc. (See this Discourse forum post .) + +### 7.3b6 7233 9 Nov 2026 - branch: main tag: mac-7.3b6 + +Added a Grayscale icons setting to Settings > Appearance — for feed icons and author avatars (article thumbnails stay in color) +Made Feed Name and Date Above Title the default in the timeline +Put the date above the thumbnail when small thumbnails and Feed Name and Date Above Title are both on +Made timeline rows always show the author or feed name, instead of leaving that spot empty +Limited articles with no title to four lines when rows show the full title with no preview +Added [[primary_media]] and [[enclosures]] tags for themes — primary_media is the article’s main image, video, or audio from the feed, when the article’s HTML doesn’t already include it +Allowed themes to include a template7.3.html file, which is used in 7.3 and later instead of template.html +Updated the built-in themes to use [[primary_media]] and [[enclosures]] +Skipped enclosure images that are the same as the feed image (as with Letters from an American), so they don’t become redundant thumbnails or primary images +Skipped primary images for microblog-style (Mastodon, etc.) posts — their images appear with the enclosures at the bottom +Used media:thumbnail as a fallback when an article has no other images (as with Wired) +Picked the widest image when Guardian image enclosures differ only by width +Fixed duplicate images in Engadget articles +Fixed embedded YouTube videos (and other iframes) not loading on sites that use Optimole lazy loading +Fixed blog.rust-lang.org articles — JavaScript is turned off for them, and their noscript content is shown +Used an item’s only Gravatar as its author’s avatar, even when the author name is a username + +### 7.3b5 7232 7 Nov 2026 - branch: main tag: mac-7.3b5 + +Added an Appearance settings pane — appearance (system, light, or dark), sidebar text size, sidebar icons, which smart feeds to show (Today, All Unread, Starred), and the article theme and text size (moved from General) +Added a Timeline settings pane — text size, feed icons (automatic, always, or never), feed icon size, thumbnails, rows (full title with no preview, or title and preview in 1 to 6 lines), separators, fading read articles, and showing the feed name and date above the title +Moved the Thumbnails setting from the View menu to Settings > Timeline +Made rows fit their content (variable row heights) in timeline +Made separators a regular setting (it was a hidden preference) — your existing choice carries over +Gave the status bar a crisper top edge, a deeper gradient, and an etched, higher-contrast divider grip +Made the main window’s split view dividers a little darker in light mode + +### 7.3b4 7229 6 Nov 2026 - branch: main tag: mac-7.3b4 + +Made small thumbnails fill the space (aspect fill) — images are cropped from the sides and bottom, never the top, so faces and other important parts are more likely to stay in view +Gave large thumbnails rounded corners, to match small thumbnails and feed icons +Removed the background color behind thumbnails, and added a faint placeholder color that shows until a thumbnail loads +Fixed footnote popover positioning near the edge of the article view and after resizing the window on Duo +Fixed bug where the last article in the timeline had a separator below it (when separators are turned on via the hidden preference) + +### 7.3b3 7227 3 Nov 2026 - branch: main tag: mac-7.3b3 + +Added support for enclosures and Media RSS +Added enclosures to the article view (at the bottom) — you can see images from Mastodon feeds, play an MP3, etc. +Made YouTube enclosures play in the privacy-enhanced YouTube player (youtube-nocookie.com) +Made the article view show plain text or media:description when an article has no HTML content +Made image downloading kinder to servers — honors Retry-After, waits after errors, and limits downloads to two at a time per host +Reorganized the View menu into sections — sidebar, timeline, status bar, and toolbar +Added article thumbnails to the timeline — choose View > Thumbnails to pick large or small. Default is none. (Works in standard layout but not column layout) + +### 7.3b2 7226 22 Oct 2026 - branch: main tag: mac-7.3b2 + +Fixed a crash at midnight when the status bar is showing +Added the last-refresh time to the status bar, and made it the default +Changed the status bar to use a shorter date format +Added Refresh and Show/Hide Sidebar commands to the status bar gear menu +Made clicking the progress indicator in the status bar open the Current Activity window (as in NetNewsWire of Yore) +Fixed bug where the status bar divider might drift from the split view divider +Fixed inline footnotes in FreshRSS articles +Added netnewswire, feed, feeds, and x-netnewswire-feed as allowed link schemes in the article view — so clicking a link to install a theme (for instance) works + +### 7.3b1 7225 20 Oct 2026 - branch: main tag: mac-7.3b1 + +Restored the status bar from NetNewsWire of Yore (NetNewsWire 1-3). Show and hide it via the View menu +Fixed extra vertical space in MacRumors articles + +### 7.2.1 7224 19 Oct 2026 - branch: main tag: mac-7.2.1 + +Same as 7.2.1b1 — just bumped the version. + +Changes since 7.2: + +Fixed bug where navigated-to row, in column layout, might appear under column headers +Fixed bug where scroller hiding/showing could mess up sidebar layout +Added magnet as an allowed link scheme + +### 7.2.1b1 7223 18 Oct 2026 - branch: main tag: mac-7.2.1b1 + +Fixed bug where navigated-to row, in column layout, might appear under column headers +Fixed bug where scroller hiding/showing could mess up sidebar layout +Added magnet as an allowed link scheme + +### 7.2 7222 14 Oct 2026 - branch: main tag: mac-7.2 + +Changes since 7.2b4: + +Fixed column view bug where next-unread could scroll to a row that’s hidden under the column headers + +Changes since 7.1.5: + +Added unread count display setting — show the count, show a dot, or hide it — which applies to the Dock icon badge, window title, and sidebar +Added column layout for the timeline — choose View > Use Column Layout +Expanded View > Sort Articles By with more options (works with standard and column layouts) +Made timeline sorting per window instead of one setting for the whole app +Made the Add Feed sheet start with the folder or account selected in the sidebar +Changed the message for adding a feed that’s already added to include the name of the folder (or folders) +Fixed bug where YouTube embeds in articles showed an error instead of playing +Fixed bug where embedded videos with no set height — such as Inoreader’s YouTube player — collapsed to a short strip +Fixed extra whitespace at the end of Slashdot articles and paragraphs running together +Fixed parsing of RSS feed titles when a feed contains a textinput section (Slashdot, for instance) +Added support for the instapaper_ignore class — elements marked with it are now removed from articles +Changed tabs in pre and code elements in articles to display as four spaces +Improved finding feeds in a page by skipping links to PDFs, movies, and other files that can’t be feeds +Changed finding a feed to use the redirected-to URL +Sped up Today and unread count queries +Added up to 500 characters of the HTTP error response body to Error Log entries +Fixed bug where the sidebar could reopen with no width when it had been collapsed in 7.1.x +Fixed a memory leak when closing a main window +Fixed a possible crash when the sidebar or timeline had no visible rows +Changed sorting by title and by feed to sort numbers by value — “Episode 2” comes before “Episode 10” +Added support for Substack-style footnotes +Improved CJK text rendering in the article view by adding text-autospace +Fixed horizontal overflow of WordPress Math blocks and SVGs in the Tiqoe Dark theme +Improved font sizing and fixed superscript orphans in table cells in the Tiqoe Dark theme + +### 7.2b4 7221 11 Oct 2026 - branch: main tag: mac-7.2b4 + +Fixed bug where embedded videos with no set height — such as Inoreader’s YouTube player — collapsed to a short strip + +### 7.2b3 7220 10 Oct 2026 - branch: main tag: mac-7.2b3 + +Fixed the Settings layout on macOS 15 +Added Spanish translations for Settings and the Sort Articles By menu +Made each Settings pane size itself to fit, for languages that need more room +Fixed bug where the sidebar could reopen with no width when it had been collapsed in 7.1.x +Fixed a memory leak when closing a main window +Fixed a possible crash when the sidebar or timeline had no visible rows +Changed sorting by title and by feed to sort numbers by value — “Episode 2” comes before “Episode 10” +Improved finding feeds in a page by skipping links to X, Twitter, Facebook, and Instagram, and links to files with uppercase extensions or URL queries (such as .PDF or .jpg?w=600) +Fixed bug where some sites with “youtube” in their names were treated as YouTube +Fixed Slashdot feed detection (for Slashdot special cases) when the feed comes through a proxy such as FeedBurner +Changed VoiceOver to say “unread” for sidebar unread counts shown as dots + ### 7.2b2 7219 7 Oct 2026 - branch: main tag: mac-7.2b2 Added support for Substack-style footnotes diff --git a/Technotes/ReleaseNotes-iOS.markdown b/Technotes/ReleaseNotes-iOS.markdown index 7c2589212..4fd61f82d 100644 --- a/Technotes/ReleaseNotes-iOS.markdown +++ b/Technotes/ReleaseNotes-iOS.markdown @@ -1,5 +1,128 @@ # iOS Release Notes +### 7.3 build 7233 9 Nov 2026 - branch: main tag: iOS-7.3-7233 + +Added Show Today, Show All Unread, and Show Starred settings, to hide smart feeds +Added a Show Feed Icons setting for the sidebar +Added a Grayscale Icons setting — for feed icons and author avatars (article thumbnails stay in color) +Added Fade Read Articles, Feed Name and Date Above Title, and Full Titles, No Preview settings to Settings > Timeline Layout +Reorganized Settings > Timeline Layout to better match the Mac version +Added a Show Previews in Context Menus setting +Made Feed Name and Date Above Title the default in the timeline +Put the date above the thumbnail when small thumbnails and Feed Name and Date Above Title are both on +Made timeline rows always show the author or feed name, instead of leaving that spot empty +Limited articles with no title to four lines when rows show the full title with no preview +Added [[primary_media]] and [[enclosures]] tags for themes — primary_media is the article’s main image, video, or audio from the feed, when the article’s HTML doesn’t already include it +Allowed themes to include a template7.3.html file, which is used in 7.3 and later instead of template.html +Updated the built-in themes to use [[primary_media]] and [[enclosures]] +Skipped enclosure images that are the same as the feed image (as with Letters from an American), so they don’t become redundant thumbnails or primary images +Skipped primary images for microblog-style (Mastodon, etc.) posts — their images appear with the enclosures at the bottom +Used media:thumbnail as a fallback when an article has no other images (as with Wired) +Picked the widest image when Guardian image enclosures differ only by width +Fixed duplicate images in Engadget articles +Fixed embedded YouTube videos (and other iframes) not loading on sites that use Optimole lazy loading +Fixed blog.rust-lang.org articles — JavaScript is turned off for them, and their noscript content is shown +Used an item’s only Gravatar as its author’s avatar, even when the author name is a username + +### 7.3 build 7231 6 Nov 2026 - branch: main tag: iOS-7.3-7231 + +Work around Apple crashing bug in iOS 27.2 beta. (Stop using <= and >= with Dates.) + +### 7.3 build 7230 6 Nov 2026 - branch: main tag: iOS-7.3-7230 + +Made separators more visible in the timeline, for real this time + +### 7.3 build 7229 6 Nov 2026 - branch: main tag: iOS-7.3-7229 + +Made small thumbnails fill the space (aspect fill) — images are cropped from the sides and bottom, never the top, so faces and other important parts are more likely to stay in view +Gave large thumbnails rounded corners, to match small thumbnails and feed icons +Removed the background color behind thumbnails, and added a faint placeholder color that shows until a thumbnail loads +Changed the background behind feed icons to the system fill color +Made the timeline separators more visible — they now use the standard iOS separator color + +### 7.3 build 7228 5 Nov 2026 - branch: main tag: iOS-7.3-7228 + +Added support for enclosures and Media RSS +Added enclosures to the article view (at the bottom) — you can see images from Mastodon feeds, play an MP3, etc. +Made YouTube enclosures play in the privacy-enhanced YouTube player (youtube-nocookie.com) +Made the article view show plain text or media:description when an article has no HTML content +Made image downloading kinder to servers — honors Retry-After, waits after errors, and limits downloads to two at a time per host +Added a Feed Icons setting to Settings > Timeline Layout — Automatic (folders, smart feeds, and authors with avatars), Always, or Never +Added article thumbnails to the timeline — choose Settings > Timeline Layout > Thumbnail Size to pick large or small. Default is none +Refreshed the Find in Article controls — translucent, with spacing that adjusts for the keyboard +Kept the reader’s place better in an article across a rotation +Made a left-edge swipe over an article reveal the timeline +Fixed the layout and resizing of the full-screen image viewer on Duo +Fixed bug with footnote popover positioning on Duo +Removed the empty navigation bar over articles when the bar buttons move to the side on iPhone Duo + +### 7.3 build 7226 22 Oct 2026 - branch: main tag: iOS-7.3-7226 + +Added an article preview to the timeline context menu — touch and hold an article to see it, and tap the preview to open the article +Added version string to the About view +Added a Copy command to the version string in Settings and in the About view — touch and hold to copy +Fixed inline footnotes in FreshRSS articles +Fixed extra vertical space in MacRumors articles +Bumped minimum iOS version from 17 to 18 + +### 7.2 build 7221 11 Oct 2026 - branch: main tag: iOS-7.2-7221 + +Submitted to App Store 15 Oct. 2026. Originally a TestFlight release. + +Changes since 7.1.4: + +Added unread count display setting — show the count, show a dot, or hide it — which applies to the app icon badge, feeds list, and widgets +Sped up Today and unread count queries +Fixed bug where the timeline selection was cleared when using the left arrow or shift-tab to go back to the feeds list (when multiple columns are showing) +Changed the selection color in the feeds list to blue when it has keyboard focus and multiple columns are showing +Fixed timeline text sometimes showing white on the gray selection background +Stopped the scroll animation when restoring the selection in the feeds list and timeline +Changed sort-by-feed to sort feed names with numbers by value — “Episode 2” comes before “Episode 10” +Fixed bug where YouTube embeds in articles showed an error instead of playing +Fixed extra whitespace at the end of Slashdot articles and paragraphs running together +Added support for the instapaper_ignore class — elements marked with it are now removed from articles +Added support for Substack-style footnotes +Improved CJK text rendering in the article view by adding text-autospace +Changed tabs in pre and code elements in articles to display as four spaces +Improved font sizing and fixed superscript orphans in table cells in the Tiqoe Dark theme +Fixed horizontal overflow of WordPress Math blocks and SVGs in the Tiqoe Dark theme +Fixed parsing of RSS feed titles when a feed contains a textinput section (Slashdot, for instance) +Fixed Slashdot feed detection (for Slashdot special cases) when the feed comes through a proxy such as FeedBurner +Improved finding feeds in a page by skipping links to PDFs, movies, and other files that can’t be feeds +Improved finding feeds in a page by skipping links to X, Twitter, Facebook, and Instagram +Changed finding a feed to use the redirected-to URL +Fixed bug where some sites with “youtube” in their names were treated as YouTube +Offered Update Credentials in the account error alert for all username and password accounts, not just Feedbin +Filled in the API URL when editing a FreshRSS account’s credentials +Removed a newly added account when its credentials can’t be saved to the keychain +Stopped account sheets from being swiped away while they’re working +Added up to 500 characters of the HTTP error response body to Error Log entries +Trimmed spaces from folder names when adding a folder + +Changes since 7.2 (7220): + +Fixed bug on iPad where fullscreen YouTube videos were black with audio only +Fixed bug where embedded videos with no set height — such as Inoreader’s YouTube player — collapsed to a short strip + +### 7.2 build 7220 10 Oct 2026 - branch: main tag: iOS-7.2-7220 + +Fixed bug where Add Feed lost the typed URL and title after choosing a folder +Offered Update Credentials in the account error alert for all username and password accounts, not just Feedbin +Filled in the API URL when editing a FreshRSS account’s credentials +Removed a newly added account when its credentials can’t be saved to the keychain +Stopped account sheets from being swiped away while they’re working +Showed unavailable rows in Add Account and the Add Feed folder picker as disabled +Trimmed spaces from folder names when adding a folder +Fixed timeline text sometimes showing white on the gray selection background +Stopped the scroll animation when restoring the selection in the feeds list and timeline +Changed sort-by-feed to sort feed names with numbers by value — “Episode 2” comes before “Episode 10” +Improved finding feeds in a page by skipping links to X, Twitter, Facebook, and Instagram, and links to files with uppercase extensions or URL queries (such as .PDF or .jpg?w=600) +Fixed bug where some sites with “youtube” in their names were treated as YouTube +Fixed Slashdot feed detection (for Slashdot special cases) when the feed comes through a proxy such as FeedBurner +Changed VoiceOver to say “unread” for unread counts shown as dots +Added VoiceOver labels and values for the Settings pop-up buttons +Told VoiceOver which folder is selected in the Add Feed folder picker + ### 7.2 build 7218 6 Oct 2026 - branch: main tag: iOS-7.2-7218 Added unread count display setting — show the count, show a dot, or hide it — which applies to the app icon badge, feeds list, and widgets diff --git a/Technotes/Status.md b/Technotes/Status.md index 70c2a4551..520a11a2c 100644 --- a/Technotes/Status.md +++ b/Technotes/Status.md @@ -5,16 +5,16 @@ https://github.com/Ranchero-Software/NetNewsWire/milestone/74 ## iOS -iOS shipping: 7.1.4 (7213) -https://github.com/Ranchero-Software/NetNewsWire/releases/tag/iOS-7.1.3-7206 +iOS shipping: 7.2 (7221) +https://github.com/Ranchero-Software/NetNewsWire/releases/tag/iOS-7.2-7221 -iOS beta: 7.2 (7218) -https://github.com/Ranchero-Software/NetNewsWire/releases/tag/iOS-7.2-7218 +iOS beta: 7.3 (7233) +https://github.com/Ranchero-Software/NetNewsWire/releases/tag/iOS-7.3-7233 ## Mac -Mac shipping: 7.1.5 -https://github.com/Ranchero-Software/NetNewsWire/releases/tag/mac-7.1.5 +Mac shipping: 7.2.1 +https://github.com/Ranchero-Software/NetNewsWire/releases/tag/mac-7.2.1 -Mac beta: 7.2b2 -https://github.com/Ranchero-Software/NetNewsWire/releases/tag/mac-7.2b2 +Mac beta: 7.3b7 +https://github.com/Ranchero-Software/NetNewsWire/releases/tag/mac-7.3b7 diff --git a/Technotes/Themes.md b/Technotes/Themes.md index 387c3cb65..c2566a542 100644 --- a/Technotes/Themes.md +++ b/Technotes/Themes.md @@ -2,9 +2,10 @@ ## `.nnwtheme` Structure -An `.nnwtheme` comprises of three files: +An `.nnwtheme` comprises of these files: - `Info.plist` - `template.html` +- `template7.3.html` (optional) - `stylesheet.css` ### Info.plist @@ -18,11 +19,69 @@ The `Info.plist` requires the following keys/types: |`CreatorName`|`String`|| |`Version`|`Integer`|| +This key is optional: + +|Key|Type|Notes| +|---|---|---| +|`grayscaleIcon`|`Boolean`|When `true`, the feed icon or author avatar in the article view is grayscale.| + +These keys are optional too. They fill in the theme's Get Info window in the Finder, and NetNewsWire ignores them: + +|Key|Type|Notes| +|---|---|---| +|`CFBundleShortVersionString`|`String`|The version, e.g. `1.2`.| +|`NSHumanReadableCopyright`|`String`|The copyright, e.g. `Copyright © 2026 Your Name`.| + ### template.html This provides a starting point for editing the structure of the page. Theme variables are documented in the header. +The page loads with the article's link as its base URL, else the feed's home page, else the feed's URL. Relative URLs resolve against that site, so a theme can't load its own `.js`, image, or font files. Put scripts inline in the template; they run only when the Article JavaScript setting is on, which is the default. Articles synced through the Google Reader API have no link of their own, so a script shouldn't assume `document.baseURI` is the article's URL. + +### template7.3.html +NetNewsWire 7.3 and later use this file instead of `template.html` when a theme includes it, and older versions ignore it. Put `[[primary_media]]` and `[[enclosures]]` here, since older versions would show them as literal text. [Verdana Revival](../Themes/Verdana%20Revival.nnwtheme/template7.3.html) is an example. + ### stylesheet.css -This provides a starting point for editing the style of the page. +This provides a starting point for editing the style of the page. + +## Article Media + +NetNewsWire 7.3 shows audio, video, and images from an article's enclosures, Media RSS, and similar elements with two tags: + +|Tag|Contents| +|---|---| +|`[[primary_media]]`|The article's main media, usually placed above the body: a video, else audio with the article's image, else the article's image. Empty when there's nothing to show.| +|`[[enclosures]]`|The article's other audio, video, and images.| + +The rules: +- The article's image is its own image, else its first image enclosure, else its thumbnail. +- Media already in the body is left out of both tags, including a resized copy of an image. +- A post with no title and a body under 2,048 characters, such as a Mastodon post, keeps its images in `[[enclosures]]`. +- A template with `[[enclosures]]` but no `[[primary_media]]` gets the article's own image in the enclosures. The thumbnail isn't shown. +- A template with no `[[enclosures]]` gets the enclosures after the body, and the body is wrapped in a `
    `, which can break selectors such as `.articleBody > p`. +- NetNewsWire looks for each tag's literal text anywhere in the template, so don't write a tag in a comment. + +The markup has no inline styles. `core.css` sets default margins, and themes can style these classes: + +```html +
    +
    + … +
    …
    +
    +
    …
    +
    + +
    +
    +
    + +
    …
    +
    +
    +
    +``` + +A video in `[[primary_media]]` uses the same `nnw-enclosure-video` block, and a YouTube video is an `

    " + + #expect(ArticleRenderer.primaryImage(imageLink: nil, thumbnailLink: nil, attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil))?.url == imageURL) + } + + // Letters from an American’s “Amanda Litman | American Conversations”: the enclosure is Substack’s still of the YouTube video the body embeds. + @Test func primaryImageSkippedWhenBodyEmbedsItsYouTubeVideo() throws { + let imageURL = "https://substackcdn.com/image/youtube/w_728,c_limit/V1DtMzaVvfA" + let attachment = try #require(Attachment(url: imageURL, mimeType: "image/jpeg", title: nil, sizeInBytes: 0, durationInSeconds: nil, width: nil, height: nil, medium: nil)) + let body = "
    " + + #expect(ArticleRenderer.primaryImage(imageLink: nil, thumbnailLink: nil, attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil)) == nil) + } + + // Mastodon: an untitled post with a short caption and a photo attachment. The photo goes in the enclosures. + @Test func shortUntitledPostHasNoPrimaryImage() throws { + let imageURL = "https://files.mastodon.social/media_attachments/files/113/464/528/402/475/066/original/7a5c5bd1e2a41a3b.jpeg" + let attachment = try #require(Attachment(url: imageURL, mimeType: "image/jpeg", title: nil, sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: .image)) + let body = "

    Fog over Lake Union this morning. The seaplanes are grounded.

    " + let bodyImageIdentities = ArticleRenderer.bodyImageIdentities(body, baseURL: nil) + + #expect(ArticleRenderer.isShortUntitledPost(title: nil, body: body)) + #expect(!ArticleRenderer.isShortUntitledPost(title: "Fog", body: body)) + #expect(ArticleRenderer.primaryMedia(imageLink: nil, thumbnailLink: nil, attachments: [attachment], articleTitle: nil, body: body, bodyImageIdentities: bodyImageIdentities, includesImage: false) == nil) + #expect(ArticleRenderer.enclosuresHTML(attachments: [attachment], body: body, bodyImageIdentities: bodyImageIdentities, posterURL: nil).contains(imageURL)) + } + + // Wired: no attachments, and the full-size lead image is in media:thumbnail. + @Test func primaryImageFallsBackToThumbnail() { + let thumbnailURL = "https://media.wired.com/photos/6aee77f4ece1c19963602401/master/pass/gear-nyt-cooking-ai-assistant.jpg" + let body = "The New York Times has added a beta feature to its Cooking app that helps readers swap ingredients or adjust recipes to suit their needs. It mostly hits the mark." + + #expect(ArticleRenderer.primaryImage(imageLink: nil, thumbnailLink: thumbnailURL, attachments: nil, body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil))?.url == thumbnailURL) + } + + // The body embeds the enclosure image, with `&` escaped in the src attribute. + @Test func imageEnclosureAlreadyInBodyIsSkipped() throws { + let imageURL = "https://storage.googleapis.com/gweb-cloudblog-publish/images/hero.max-1000x1000.png?w=1000&h=500" + let attachment = try #require(Attachment(url: imageURL, mimeType: nil, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: 1000, height: 500, medium: .image)) + let body = "

    " + + let html = ArticleRenderer.enclosuresHTML(attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil), posterURL: nil) + + #expect(html.isEmpty) + } + + // The Atlantic’s “Look Closer: A Mysterious Pair of Mittens”: the media:content image is a crop of the body’s photo. + @Test func imageEnclosureCopyInBodyIsSkipped() throws { + let imageURL = "https://cdn.theatlantic.com/thumbor/uIb4bjseN9GStI6B22iXaQrrOQU=/0x936:2400x2287/media/img/2026/11/Mittens_hi_res/original.jpg" + let attachment = try #require(Attachment(url: imageURL, mimeType: nil, title: nil, sizeInBytes: nil, durationInSeconds: nil, width: nil, height: nil, medium: nil)) + let body = "
    \"a
    " + + let html = ArticleRenderer.enclosuresHTML(attachments: [attachment], body: body, bodyImageIdentities: ArticleRenderer.bodyImageIdentities(body, baseURL: nil), posterURL: nil) + + #expect(html.isEmpty) + } +} diff --git a/Tests/NetNewsWireTests/SharingTests.swift b/Tests/NetNewsWireTests/SharingTests.swift index 5f9814078..db89cbb01 100644 --- a/Tests/NetNewsWireTests/SharingTests.swift +++ b/Tests/NetNewsWireTests/SharingTests.swift @@ -52,9 +52,11 @@ import XCTest externalURL: nil, summary: nil, imageURL: nil, + thumbnailURL: nil, datePublished: nil, dateModified: nil, authors: nil, + attachments: nil, status: ArticleStatus(articleID: articleId, read: true, dateArrived: Date()) ) } diff --git a/Tests/NetNewsWireTests/TimelineCellLayoutTests.swift b/Tests/NetNewsWireTests/TimelineCellLayoutTests.swift new file mode 100644 index 000000000..dec76f570 --- /dev/null +++ b/Tests/NetNewsWireTests/TimelineCellLayoutTests.swift @@ -0,0 +1,45 @@ +// +// TimelineCellLayoutTests.swift +// NetNewsWireTests +// +// Created by Brent Simmons on 11/7/26. +// + +import AppKit +import Articles +import Testing + +@testable import NetNewsWire + +@MainActor struct TimelineCellLayoutTests { + + @Test func feedNameAndDateAboveTitle() { + let appearance = TimelineCellAppearance(showIcon: true, textSize: .medium, iconSize: .large, numberOfLines: 3, showsFullTitles: false, feedNameAndDateAboveTitle: true, showsLargeThumbnails: false) + let cellData = TimelineCellData(article: makeArticle(), showFeedName: .feed, feedName: "Daring Fireball", byline: nil, iconImage: nil, showIcon: true, thumbnail: nil, showThumbnail: false) + + let layout = TimelineCellLayout(width: 400.0, height: 0.0, cellData: cellData, appearance: appearance) + + #expect(layout.dateRect.maxY <= layout.titleRect.minY) + #expect(layout.feedNameRect.minY == layout.dateRect.minY) + } + + @Test func smallThumbnailAlignsWithTitleWhenFeedNameAndDateAboveTitle() { + let appearance = TimelineCellAppearance(showIcon: true, textSize: .medium, iconSize: .large, numberOfLines: 3, showsFullTitles: false, feedNameAndDateAboveTitle: true, showsLargeThumbnails: false) + let cellData = TimelineCellData(article: makeArticle(), showFeedName: .feed, feedName: "Daring Fireball", byline: nil, iconImage: nil, showIcon: true, thumbnail: nil, showThumbnail: true) + let width: CGFloat = 400.0 + + let layout = TimelineCellLayout(width: width, height: 0.0, cellData: cellData, appearance: appearance) + + #expect(layout.thumbnailRect.minY == layout.titleRect.minY) + #expect(layout.dateRect.maxX == width - appearance.cellPadding.right) + #expect(layout.dateRect.maxY <= layout.thumbnailRect.minY) + } +} + +// MARK: - Helpers + +@MainActor private func makeArticle() -> Article { + let articleID = "article1" + let status = ArticleStatus(articleID: articleID, read: false, starred: false, dateArrived: Date()) + return Article(accountID: "account1", articleID: articleID, feedID: "feed1", uniqueID: articleID, title: "Apple Announces New MacBook Pro Models", contentHTML: "

    The new models are available to order today.

    ", contentText: nil, markdown: nil, url: nil, externalURL: nil, summary: nil, imageURL: nil, thumbnailURL: nil, datePublished: Date(), dateModified: nil, authors: nil, attachments: nil, status: status) +} diff --git a/Tests/NetNewsWireTests/TimelineRowHeightPerformanceTests.swift b/Tests/NetNewsWireTests/TimelineRowHeightPerformanceTests.swift new file mode 100644 index 000000000..341814656 --- /dev/null +++ b/Tests/NetNewsWireTests/TimelineRowHeightPerformanceTests.swift @@ -0,0 +1,93 @@ +// +// TimelineRowHeightPerformanceTests.swift +// NetNewsWireTests +// +// Created by Brent Simmons on 11/7/26. +// + +import AppKit +import Articles +import Images +import XCTest + +@testable import NetNewsWire + +/// What one timeline row height costs, including building its cell data, as the timeline’s +/// heightOfRow would. NSTableView asks for every row’s height when it reloads. +/// +/// Cold: each pass uses articles it hasn’t seen, so text measuring isn’t cached. +/// Warm: each pass uses the same articles, as after a reload at the same width. +/// +/// Benchmark: release build, Apple Silicon, 3,000 articles at 400 points wide: +/// +/// Test Total Per row +/// ------- ------------ ------------- +/// Cold 0.321 s 0.000107 s +/// Warm 0.024 s 0.000008 s +/// +@MainActor final class TimelineRowHeightPerformanceTests: XCTestCase { + + private static let articleCount = 3000 + private static let rowWidth: CGFloat = 400.0 + private static let warmArticles = makeTimelineArticles(count: articleCount, pass: 0) + + func testRowHeightsCold() { + var pass = 1 + measureMetrics([.wallClockTime], automaticallyStartMeasuring: false) { + let articles = makeTimelineArticles(count: Self.articleCount, pass: pass) + pass += 1 + startMeasuring() + Self.calculateRowHeights(articles) + stopMeasuring() + } + } + + func testRowHeightsWarm() { + Self.calculateRowHeights(Self.warmArticles) + measure { + Self.calculateRowHeights(Self.warmArticles) + } + } +} + +// MARK: - Helpers + +private extension TimelineRowHeightPerformanceTests { + + static let appearance = TimelineCellAppearance(showIcon: true, textSize: .medium, iconSize: .large, numberOfLines: 3, showsFullTitles: false, feedNameAndDateAboveTitle: false, showsLargeThumbnails: false) + + static func calculateRowHeights(_ articles: [Article]) { + for article in articles { + let cellData = TimelineCellData(article: article, showFeedName: .feed, feedName: "Feed Name", byline: nil, iconImage: nil, showIcon: true, thumbnail: nil, showThumbnail: false) + _ = TimelineCellLayout.height(for: rowWidth, cellData: cellData, appearance: appearance) + } + } +} + +/// Titles and summaries of varied length. `pass` makes every string unique to that pass. +@MainActor private func makeTimelineArticles(count: Int, pass: Int) -> [Article] { + let sampleTitles = [ + "Short title", + "A title of moderate length that probably wraps onto a second line", + "A long title that goes on for quite a while, the way some sites write them, so that it needs three or four lines in a narrow timeline", + "", + "Title with bold and italic and émoji 🎉" + ] + let sampleBodies = [ + "

    A short body.

    ", + "

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.

    ", + "

    A body with a link and some & entities, long enough to fill a preview with a couple of lines of text.

    " + ] + var articles = [Article]() + articles.reserveCapacity(count) + for i in 0..", with: " \(pass)-\(i)

    ") + let status = ArticleStatus(articleID: articleID, read: false, starred: false, dateArrived: Date()) + let article = Article(accountID: "account1", articleID: articleID, feedID: "feed1", uniqueID: articleID, title: uniqueTitle, contentHTML: body, contentText: nil, markdown: nil, url: nil, externalURL: nil, summary: nil, imageURL: nil, thumbnailURL: nil, datePublished: Date(), dateModified: nil, authors: nil, attachments: nil, status: status) + articles.append(article) + } + return articles +} diff --git a/Resources/Themes/Appanoose.nnwtheme/template.html b/Themes/Appanoose.nnwtheme/template7.3.html similarity index 97% rename from Resources/Themes/Appanoose.nnwtheme/template.html rename to Themes/Appanoose.nnwtheme/template7.3.html index acc460be6..13d3e6400 100644 --- a/Resources/Themes/Appanoose.nnwtheme/template.html +++ b/Themes/Appanoose.nnwtheme/template7.3.html @@ -45,7 +45,9 @@
    + [[primary_media]]
    [[body]]
    + [[enclosures]]
    + [[primary_media]]
    [[body]]
    + [[enclosures]]
    diff --git a/Resources/Themes/Appanoose.nnwtheme/Info.plist b/Themes/Gray.nnwtheme/Info.plist similarity index 71% rename from Resources/Themes/Appanoose.nnwtheme/Info.plist rename to Themes/Gray.nnwtheme/Info.plist index dd069dcaa..20baa80d3 100644 --- a/Resources/Themes/Appanoose.nnwtheme/Info.plist +++ b/Themes/Gray.nnwtheme/Info.plist @@ -3,14 +3,16 @@ Name - Appanoose + Gray ThemeIdentifier - com.netnewswire.themes.starter + com.netnewswire.themes.gray CreatorHomePage - http://netnewswire.com/ + https://netnewswire.com/ CreatorName Ranchero Software Version 1 + grayscaleIcon + diff --git a/Resources/Themes/Verdana Revival.nnwtheme/stylesheet.css b/Themes/Gray.nnwtheme/stylesheet.css similarity index 52% rename from Resources/Themes/Verdana Revival.nnwtheme/stylesheet.css rename to Themes/Gray.nnwtheme/stylesheet.css index 4ee29c994..6f733bdd1 100644 --- a/Resources/Themes/Verdana Revival.nnwtheme/stylesheet.css +++ b/Themes/Gray.nnwtheme/stylesheet.css @@ -1,16 +1,14 @@ -/* Verdana Revival — inspired by netnewswire.com and netnewswire.blog */ +/* Gray is inspired by, but not a literal copy of, newsprint. */ body { + margin: 0 0 20px; + padding: 0; word-wrap: break-word; } -article { - margin-top: 16px; -} - a { text-decoration: none; - text-underline-offset: 0.1em; + text-underline-offset: 3px; } .systemMessage { @@ -23,50 +21,59 @@ a { } :root { - --background-color: #fafafb; - --text-color: #2a2e3a; - --link-color: #2670c4; - --visited-link-color: #7b5ea7; - --attribution-color: #6a7080; - --article-title-color: #2a2e3a; - --body-code-color: #555e6a; + color-scheme: light dark; + + --body-font: Georgia, 'Times New Roman', serif; + --heading-font: 'Helvetica Neue', Helvetica, sans-serif; + --mono-font: "SF Mono", Menlo, "Courier New", Courier, monospace; + + --background-color: #f4f4f4; + --text-color: #2a2a2a; + --link-color: #1a1a1a; + --visited-link-color: #7a7a7a; + --article-title-color: #2a2a2a; + --attribution-color: #6e6e6e; + --separator-color: #d8d8d8; + --table-cell-border-color: #d8d8d8; + --blockquote-border-color: #a8a8a8; + --blockquote-text-color: #5c5c5c; + --body-code-color: #4a4a4a; --body-code-background: rgba(0, 0, 0, 0.05); - --system-message-color: #b0b4bc; - --separator-color: #d4dce8; - --table-cell-border-color: #d4dce8; - --blockquote-border-color: #e8a820; - --blockquote-text-color: rgba(0, 0, 0, 0.7); - --blockquote-background: rgba(0, 0, 0, 0.02); - --footer-color: #6a7080; --pre-background: rgba(0, 0, 0, 0.04); - --header-top: #3b8de0; - --header-bottom: #2b6fc0; - --dateline-bar-top: #e8a820; - --dateline-bar-bottom: #d49618; + --system-message-color: #b0b0b0; + --footer-color: #6e6e6e; + --header-background: #2e2e2e; + --header-title-color: #fff; + --nav-background: #555555; + --byline-color: #f5f5f5; + --footnote-popover-border: #d8d8d8; + --footnote-popover-background: #fbfbfb; + --footnote-color: #8a8a8a; } @media(prefers-color-scheme: dark) { :root { - --background-color: #181c22; - --text-color: #c4ccd5; - --link-color: #4a8ad4; - --visited-link-color: #c4a050; - --attribution-color: #8894a0; - --article-title-color: #dce0e6; - --body-code-color: #a0a8b2; - --body-code-background: rgba(255, 255, 255, 0.08); - --system-message-color: #5f646c; - --separator-color: rgba(255, 255, 255, 0.12); - --table-cell-border-color: rgba(255, 255, 255, 0.15); - --blockquote-border-color: #a07818; - --blockquote-text-color: rgba(255, 255, 255, 0.7); - --blockquote-background: rgba(255, 255, 255, 0.03); - --footer-color: #8894a0; - --pre-background: rgba(255, 255, 255, 0.06); - --header-top: #2968aa; - --header-bottom: #1f528c; - --dateline-bar-top: #a07818; - --dateline-bar-bottom: #886412; + --background-color: #1a1a1a; + --text-color: #dadada; + --link-color: #f2f2f2; + --visited-link-color: #888888; + --article-title-color: #ececec; + --attribution-color: #9a9a9a; + --separator-color: #2e2e2e; + --table-cell-border-color: #383838; + --blockquote-border-color: #6a6a6a; + --blockquote-text-color: #a0a0a0; + --body-code-color: #b4b4b4; + --body-code-background: rgba(255, 255, 255, 0.07); + --pre-background: rgba(255, 255, 255, 0.05); + --system-message-color: #5c5c5c; + --footer-color: #9a9a9a; + --header-background: #363636; + --nav-background: #2a2a2a; + --byline-color: #eeeeee; + --footnote-popover-border: #383838; + --footnote-popover-background: #242424; + --footnote-color: #6e6e6e; } } @@ -85,18 +92,19 @@ body a:visited { body > .systemMessage { color: var(--system-message-color); + font-family: var(--heading-font); } -/* Header bar — blue gradient with favicon, site name, author */ +/* Header bar — dark gray, with favicon and site name */ .headerBar { - background: linear-gradient(to bottom, var(--header-top), var(--header-bottom)); + background-color: var(--header-background); padding: 14px 0; - font-size: 1em; + font-family: var(--heading-font); + font-size: 1.2em; font-weight: bold; - line-height: 1.4; - color: white; - text-shadow: 0 1px 1px rgba(0, 0, 0, 0.25); + line-height: 1.2; + color: var(--header-title-color); } .headerBarInner { @@ -105,79 +113,85 @@ body > .systemMessage { } .avatar { - vertical-align: middle; + flex-shrink: 0; + width: 1.5em; + height: 1.5em !important; + margin: 0 0.5em 0 0; border-radius: 3px; - height: 1.8em !important; - width: 1.8em; - min-width: 1.8em; - margin: 0 !important; - margin-right: 0.5em !important; } -.headerBar a:link, .headerBar a:visited, .headerBar a, .feedlink { - color: white !important; - font-weight: bold; +.headerBar a, .headerBar a:visited { + color: var(--header-title-color); } .headerBar a:hover { text-decoration: underline; } -.byline { - color: rgba(255, 255, 255, 0.7); - margin-left: 0.5em; +/* Nav bar — medium gray, with date at the left and byline at the right */ + +.navBar { + background-color: var(--nav-background); + padding: 6px 0; + font-family: var(--heading-font); + font-size: 0.85em; + font-weight: bold; + line-height: 1.4; + color: var(--byline-color); } -body .byline a:link, .byline a:visited, .byline a { - color: rgba(255, 255, 255, 0.7) !important; +.navBarInner { + display: flex; + align-items: baseline; + gap: 1em; +} + +.navBar .dateline { + font-size: 0.9em; + font-weight: 500; + letter-spacing: 0.06em; + text-transform: uppercase; + opacity: 0.9; +} + +.byline { + margin-left: auto; + text-align: right; +} + +/* Zero-width space: an empty byline still has a baseline, so the date doesn’t shift */ +.byline::after { + content: "\200B"; +} + +.navBar a, .navBar a:visited { + color: var(--byline-color); +} + +.navBar a:hover { + text-decoration: underline; } /* Content containers */ .barContent, .articleContent { - max-width: 44rem; + max-width: 40rem; margin-left: auto; margin-right: auto; } .articleContent { - margin-top: 2em; -} - -/* Dateline bar — gradient with date */ - -.datelineBar { - background: linear-gradient(to bottom, var(--dateline-bar-top), var(--dateline-bar-bottom)); - padding: 8px 0; - font-size: 0.85em; - font-weight: bold; - line-height: 1.4; - color: white; -} - -.datelineBarInner { - display: flex; - align-items: center; - justify-content: flex-start; -} - -.datelineDate a:link, .datelineDate a:visited, .datelineDate a { - color: white !important; - font-weight: bold; -} - -.datelineBar a:hover { - text-decoration: underline; + margin-top: 1.5em; } /* Article title */ .articleTitle { - font-size: 1.5em; + font-family: var(--heading-font); + font-size: 1.4em; font-weight: bold; - line-height: 1.25; - margin-top: 0; - margin-bottom: 16px; + line-height: 1.2; + margin-bottom: 20px; color: var(--article-title-color); } @@ -192,12 +206,17 @@ body .byline a:link, .byline a:visited, .byline a { /* Article body */ .articleBody { - margin-top: 24px; - line-height: 1.8em; + line-height: 1.7em; } -.articleBody a { +.articleBody a, .footer a { text-decoration: underline; + text-decoration-thickness: 1px; + text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); +} + +.articleBody a:hover, .footer a:hover { + text-decoration-color: currentColor; } .articleBody p { @@ -206,21 +225,22 @@ body .byline a:link, .byline a:visited, .byline a { /* Footer */ -body .footer { +.footer { margin-top: 28px; margin-bottom: 2em; + font-family: var(--heading-font); color: var(--footer-color); - font-size: 0.85em; - font-style: italic; + font-size: 0.8em; } -body .footer a:link, .footer a:visited { - color: var(--link-color); - text-decoration: underline; +.footer a, .footer a:visited { + color: var(--text-color); } +/* Room below the line, so .singleLine’s overflow: hidden doesn’t clip the link underline */ .externalLink { width: 100%; + padding-bottom: 4px; } .singleLine { @@ -231,29 +251,30 @@ body .footer a:link, .footer a:visited { /* Headings */ -h1 { +h1, h2, h3, h4, h5, h6 { + font-family: var(--heading-font); line-height: 1.2em; font-weight: bold; - padding-bottom: 0; +} + +h1 { margin-bottom: 8px; } h2 { line-height: 1.25em; - font-weight: bold; margin-bottom: 6px; } h3 { - font-weight: bold; margin-bottom: 4px; } /* Code */ code, pre { - font-family: "SF Mono", Menlo, "Courier New", Courier, monospace; - font-size: 0.9em; + font-family: var(--mono-font); + font-size: 0.85em; -webkit-hyphens: none; } @@ -276,7 +297,7 @@ pre { word-break: normal; line-height: 1.5em; background: var(--pre-background); - padding: 10px; + padding: 8px 12px; border-radius: 4px; } @@ -287,15 +308,13 @@ pre code { padding: 0; } -/* Blockquotes — amber border */ +/* Blockquotes */ blockquote { margin-inline-start: 0; margin-inline-end: 0; - padding: 0.8em 1em; - border-inline-start: 2px solid var(--blockquote-border-color); - background: var(--blockquote-background); - border-radius: 0 4px 4px 0; + padding-left: 18px; + border-inline-start: 3px solid var(--blockquote-border-color); color: var(--blockquote-text-color); } @@ -309,8 +328,6 @@ blockquote > *:last-child { blockquote > blockquote { padding-left: 1em; - padding-top: 0; - padding-bottom: 0; font-style: italic; } @@ -323,7 +340,7 @@ blockquote > blockquote { .nnw-overflow table { margin-bottom: 1px; border-spacing: 0; - border: 1px solid var(--separator-color); + border: 1px solid var(--table-cell-border-color); font-size: inherit; } @@ -341,11 +358,15 @@ blockquote > blockquote { padding: 5px; } -.nnw-overflow tr :matches(td, th):last-child { +.nnw-overflow th { + font-family: var(--heading-font); +} + +.nnw-overflow tr :is(td, th):last-child { border-right: none; } -.nnw-overflow :matches(thead, tbody, tfoot):last-child > tr:last-child :matches(td, th) { +.nnw-overflow :is(thead, tbody, tfoot):last-child > tr:last-child :is(td, th) { border-bottom: none; } @@ -381,7 +402,8 @@ figure { } figcaption { - font-size: 0.85em; + font-family: var(--heading-font); + font-size: 0.8em; line-height: 1.3em; color: var(--attribution-color); } @@ -429,87 +451,57 @@ hr { /* Newsfoot footnote popovers */ .newsfoot-footnote-popover { - background: #d4dce8; + background: var(--footnote-popover-border); box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3), 0 3px 6px rgba(0, 0, 0, 0.15); - color: #2a2e3a; + color: var(--text-color); padding: 1px; } .newsfoot-footnote-popover-arrow { - background: #fafcff; - border: 1px solid #d4dce8; + background: var(--footnote-popover-background); + border: 1px solid var(--footnote-popover-border); } .newsfoot-footnote-popover-inner { - background: #fafcff; + background: var(--footnote-popover-background); } body a.footnote, body a.footnote:visited, .newsfoot-footnote-popover + a.footnote:hover { - background: #8894a0; + background: var(--footnote-color); color: white; transition: background-color 200ms ease-out; } -a.footnote:hover, -.newsfoot-footnote-popover + a.footnote { - background: #2670c4; - transition: background-color 200ms ease-out; +/* Overrides the .articleBody a underline */ +.articleBody a.footnote { + text-decoration: none; } -@media screen and (prefers-color-scheme: dark) { - .newsfoot-footnote-popover { - background: #2e3440; - color: #c4ccd5; - } - - .newsfoot-footnote-popover-arrow { - background: #1e2430; - border: 1px solid #2e3440; - } - - .newsfoot-footnote-popover-inner { - background: #1e2430; - } - - body a.footnote, - body a.footnote:visited, - .newsfoot-footnote-popover + a.footnote:hover { - background: #8894a0; - color: white; - transition: background-color 200ms ease-out; - } - - a.footnote:hover, - .newsfoot-footnote-popover + a.footnote { - background: #4a8ad4; - transition: background-color 200ms ease-out; - } +a.footnote:hover, +.newsfoot-footnote-popover + a.footnote { + background: var(--header-background); + transition: background-color 200ms ease-out; } /* iOS Specific */ @supports (-webkit-touch-callout: none) { body { - margin: 0; - padding: 0; - margin-bottom: 20px; - word-break: break-word; -webkit-hyphens: auto; -webkit-text-size-adjust: none; } :root { - color-scheme: light dark; - font-family: Verdana, Geneva, sans-serif; + font-family: var(--body-font); /* The font-size is replaced at runtime by the dynamic type size */ font-size: [[font-size]]px; } .fontSize { - font-family: Verdana, Geneva, sans-serif; + font-family: var(--body-font); font-size: [[font-size]]px; } @@ -517,24 +509,13 @@ a.footnote:hover, padding-left: 20px; padding-right: 20px; } - - pre { - border: none; - } - - .nnw-overflow table { - border: 1px solid var(--separator-color); - } } /* macOS Specific */ @supports not (-webkit-touch-callout: none) { body { - margin: 0; - padding: 0; - margin-bottom: 20px; - font-family: Verdana, Geneva, sans-serif; + font-family: var(--body-font); } .articleContent, .barContent { @@ -543,34 +524,22 @@ a.footnote:hover, } .smallText { - font-size: 14px; + font-size: 15px; } .mediumText { - font-size: 16px; + font-size: 17px; } .largeText { - font-size: 18px; + font-size: 19px; } .xlargeText { - font-size: 20px; + font-size: 21px; } .xxlargeText { - font-size: 22px; - } - - :root { - color-scheme: light dark; - } - - pre { - border: none; - } - - .nnw-overflow table { - border: 1px solid var(--separator-color); + font-size: 23px; } } diff --git a/Themes/Gray.nnwtheme/template.html b/Themes/Gray.nnwtheme/template.html new file mode 100644 index 000000000..69f92406e --- /dev/null +++ b/Themes/Gray.nnwtheme/template.html @@ -0,0 +1,34 @@ +
    + + + + + +
    + +
    + [[title]] +
    + +
    +
    [[body]]
    +
    + + +
    + +
    diff --git a/Themes/Gray.nnwtheme/template7.3.html b/Themes/Gray.nnwtheme/template7.3.html new file mode 100644 index 000000000..d10389124 --- /dev/null +++ b/Themes/Gray.nnwtheme/template7.3.html @@ -0,0 +1,36 @@ +
    + + + + + +
    + +
    + [[title]] +
    + +
    + [[primary_media]] +
    [[body]]
    + [[enclosures]] +
    + + +
    + +
    diff --git a/Resources/Themes/Hyperlegible.nnwtheme/template.html b/Themes/Hyperlegible.nnwtheme/template7.3.html similarity index 98% rename from Resources/Themes/Hyperlegible.nnwtheme/template.html rename to Themes/Hyperlegible.nnwtheme/template7.3.html index a8bbed925..0a76fe970 100644 --- a/Resources/Themes/Hyperlegible.nnwtheme/template.html +++ b/Themes/Hyperlegible.nnwtheme/template7.3.html @@ -43,5 +43,7 @@ body: The body of the article. +[[primary_media]]
    [[body]]
    +[[enclosures]]
    diff --git a/Resources/Themes/NewsFax.nnwtheme/template.html b/Themes/NewsFax.nnwtheme/template7.3.html similarity index 99% rename from Resources/Themes/NewsFax.nnwtheme/template.html rename to Themes/NewsFax.nnwtheme/template7.3.html index c50f40bb0..7d9dc1bb4 100644 --- a/Resources/Themes/NewsFax.nnwtheme/template.html +++ b/Themes/NewsFax.nnwtheme/template7.3.html @@ -51,7 +51,9 @@ body: The body of the article.
    +[[primary_media]]
    [[body]]
    +[[enclosures]] diff --git a/Resources/Themes/Sepia.nnwtheme/Info.plist b/Themes/Plum.nnwtheme/Info.plist similarity index 76% rename from Resources/Themes/Sepia.nnwtheme/Info.plist rename to Themes/Plum.nnwtheme/Info.plist index 6ad2fab65..548607f7b 100644 --- a/Resources/Themes/Sepia.nnwtheme/Info.plist +++ b/Themes/Plum.nnwtheme/Info.plist @@ -3,11 +3,11 @@ Name - Sepia + Plum ThemeIdentifier - com.netnewswire.themes.sepia + com.netnewswire.themes.plum CreatorHomePage - http://netnewswire.com/ + https://netnewswire.com/ CreatorName Ranchero Software Version diff --git a/Themes/Plum.nnwtheme/stylesheet.css b/Themes/Plum.nnwtheme/stylesheet.css new file mode 100644 index 000000000..77b298735 --- /dev/null +++ b/Themes/Plum.nnwtheme/stylesheet.css @@ -0,0 +1,547 @@ +/* Plum shares its layout with the Gray theme and differs only in color. + To make your own variation, start with the color variables in :root + and in the dark-mode block below it. */ + +body { + margin: 0 0 20px; + padding: 0; + word-wrap: break-word; +} + +a { + text-decoration: none; + text-underline-offset: 3px; +} + +.systemMessage { + position: absolute; + top: 45%; + left: 50%; + transform: translateX(-55%) translateY(-50%); + -webkit-user-select: none; + cursor: default; +} + +:root { + color-scheme: light dark; + + --body-font: Georgia, 'Times New Roman', serif; + --heading-font: 'Helvetica Neue', Helvetica, sans-serif; + --mono-font: "SF Mono", Menlo, "Courier New", Courier, monospace; + + --background-color: #f4f3f6; + --text-color: #2a2833; + --link-color: #3446b8; + --visited-link-color: #8a2f7a; + --article-title-color: #2a2833; + --attribution-color: #6e6a7a; + --separator-color: #d9d6e0; + --table-cell-border-color: #d9d6e0; + --blockquote-border-color: #e5a823; + --blockquote-text-color: #5c5a66; + --body-code-color: #4a4766; + --body-code-background: rgba(61, 31, 63, 0.06); + --pre-background: rgba(61, 31, 63, 0.05); + --system-message-color: #b2aebd; + --footer-color: #6e6a7a; + --header-background: #3d1f3f; + --header-title-color: #fff; + --nav-background: #a8402e; + --byline-color: #f5eefa; + --footnote-popover-border: #d9d6e0; + --footnote-popover-background: #fbfafc; + --footnote-color: #8a8597; +} + +@media(prefers-color-scheme: dark) { + :root { + --background-color: #1a1824; + --text-color: #dcd9e6; + --link-color: #9fb0ff; + --visited-link-color: #f0a6e0; + --article-title-color: #ece9f4; + --attribution-color: #9a96aa; + --separator-color: #2c2940; + --table-cell-border-color: #36324c; + --blockquote-border-color: #c99a2a; + --blockquote-text-color: #a09cb0; + --body-code-color: #b4b0cc; + --body-code-background: rgba(255, 255, 255, 0.07); + --pre-background: rgba(255, 255, 255, 0.05); + --system-message-color: #5c586c; + --footer-color: #9a96aa; + --header-background: #432448; + --nav-background: #5c271d; + --byline-color: #ece6f6; + --footnote-popover-border: #36324c; + --footnote-popover-background: #24212f; + --footnote-color: #6e6a7a; + } +} + +body { + background-color: var(--background-color); + color: var(--text-color); +} + +body a, body a * { + color: var(--link-color); +} + +body a:visited { + color: var(--visited-link-color); +} + +body > .systemMessage { + color: var(--system-message-color); + font-family: var(--heading-font); +} + +/* Header bar — plum, with favicon and site name */ + +.headerBar { + background-color: var(--header-background); + padding: 14px 0; + font-family: var(--heading-font); + font-size: 1.2em; + font-weight: bold; + line-height: 1.2; + color: var(--header-title-color); +} + +.headerBarInner { + display: flex; + align-items: center; +} + +.avatar { + flex-shrink: 0; + width: 1.5em; + height: 1.5em !important; + margin: 0 0.5em 0 0; + border-radius: 3px; +} + +.headerBar a, .headerBar a:visited { + color: var(--header-title-color); +} + +.headerBar a:hover { + text-decoration: underline; +} + +/* Nav bar — maroon, with date at the left and byline at the right */ + +.navBar { + background-color: var(--nav-background); + padding: 6px 0; + font-family: var(--heading-font); + font-size: 0.85em; + font-weight: bold; + line-height: 1.4; + color: var(--byline-color); +} + +.navBarInner { + display: flex; + align-items: baseline; + gap: 1em; +} + +.navBar .dateline { + font-size: 0.9em; + font-weight: 500; + letter-spacing: 0.06em; + text-transform: uppercase; + opacity: 0.9; +} + +.byline { + margin-left: auto; + text-align: right; +} + +/* Zero-width space: an empty byline still has a baseline, so the date doesn’t shift */ +.byline::after { + content: "\200B"; +} + +.navBar a, .navBar a:visited { + color: var(--byline-color); +} + +.navBar a:hover { + text-decoration: underline; +} + +/* Content containers */ + +.barContent, .articleContent { + max-width: 40rem; + margin-left: auto; + margin-right: auto; +} + +.articleContent { + margin-top: 1.5em; +} + +/* Article title */ + +.articleTitle { + font-family: var(--heading-font); + font-size: 1.4em; + font-weight: bold; + line-height: 1.2; + margin-bottom: 20px; + color: var(--article-title-color); +} + +.articleTitle a:link, .articleTitle a:visited, .articleTitle a { + color: var(--article-title-color); +} + +.articleTitle a:hover { + text-decoration: underline; +} + +/* Article body */ + +.articleBody { + line-height: 1.7em; +} + +.articleBody a, .footer a { + text-decoration: underline; + text-decoration-thickness: 1px; + text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); +} + +.articleBody a:hover, .footer a:hover { + text-decoration-color: currentColor; +} + +.articleBody p { + margin-bottom: 1em; +} + +/* Footer */ + +.footer { + margin-top: 28px; + margin-bottom: 2em; + font-family: var(--heading-font); + color: var(--footer-color); + font-size: 0.8em; +} + +.footer a, .footer a:visited { + color: var(--link-color); +} + +/* Room below the line, so .singleLine’s overflow: hidden doesn’t clip the link underline */ +.externalLink { + width: 100%; + padding-bottom: 4px; +} + +.singleLine { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* Headings */ + +h1, h2, h3, h4, h5, h6 { + font-family: var(--heading-font); + line-height: 1.2em; + font-weight: bold; +} + +h1 { + margin-bottom: 8px; +} + +h2 { + line-height: 1.25em; + margin-bottom: 6px; +} + +h3 { + margin-bottom: 4px; +} + +/* Code */ + +code, pre { + font-family: var(--mono-font); + font-size: 0.85em; + -webkit-hyphens: none; +} + +body code, body pre { + color: var(--body-code-color); +} + +p code { + background: var(--body-code-background); + padding: 0.15em 0.35em; + border-radius: 3px; +} + +pre { + max-width: 100%; + margin: 0; + overflow: auto; + overflow-y: hidden; + word-wrap: normal; + word-break: normal; + line-height: 1.5em; + background: var(--pre-background); + padding: 8px 12px; + border-radius: 4px; +} + +pre code { + letter-spacing: -.027em; + font-size: 0.9375em; + background: none; + padding: 0; +} + +/* Blockquotes — gold border */ + +blockquote { + margin-inline-start: 0; + margin-inline-end: 0; + padding-left: 18px; + border-inline-start: 3px solid var(--blockquote-border-color); + color: var(--blockquote-text-color); +} + +blockquote > *:first-child { + margin-block-start: 0; +} + +blockquote > *:last-child { + margin-block-end: 0; +} + +blockquote > blockquote { + padding-left: 1em; + font-style: italic; +} + +/* Tables */ + +.nnw-overflow { + overflow-x: auto; +} + +.nnw-overflow table { + margin-bottom: 1px; + border-spacing: 0; + border: 1px solid var(--table-cell-border-color); + font-size: inherit; +} + +.nnw-overflow table table { + margin-bottom: 0; + border: none; +} + +.nnw-overflow td, .nnw-overflow th { + -webkit-hyphens: none; + word-break: normal; + border: 1px solid var(--table-cell-border-color); + border-top: none; + border-left: none; + padding: 5px; +} + +.nnw-overflow th { + font-family: var(--heading-font); +} + +.nnw-overflow tr :is(td, th):last-child { + border-right: none; +} + +.nnw-overflow :is(thead, tbody, tfoot):last-child > tr:last-child :is(td, th) { + border-bottom: none; +} + +.nnw-overflow td pre { + border: none; + padding: 0; +} + +.nnw-overflow table[border="0"] { + border-width: 0; +} + +/* Media elements */ + +img, figure, video, div, object { + max-width: 100%; + height: auto !important; + margin: 0 auto; +} + +iframe { + max-width: 100%; + margin: 0 auto; +} + +iframe.nnw-constrained { + max-height: 50vw; +} + +figure { + margin-bottom: 1em; + margin-top: 1em; +} + +figcaption { + font-family: var(--heading-font); + font-size: 0.8em; + line-height: 1.3em; + color: var(--attribution-color); +} + +sup { + vertical-align: top; + position: relative; + bottom: 0.2rem; +} + +sub { + vertical-align: bottom; + position: relative; + top: 0.2rem; +} + +hr { + border: none; + background-color: var(--separator-color); + height: 1px; + margin-top: 1.5em; + margin-bottom: 1.5em; +} + +.iframeWrap { + position: relative; + display: block; + padding-top: 56.25%; +} + +.iframeWrap iframe { + position: absolute; + top: 0; + left: 0; + height: 100% !important; + width: 100% !important; +} + +/* Feed specific */ + +.feedbin--article-wrap { + border-top: 1px solid var(--separator-color); +} + +/* Newsfoot footnote popovers */ + +.newsfoot-footnote-popover { + background: var(--footnote-popover-border); + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3), 0 3px 6px rgba(0, 0, 0, 0.15); + color: var(--text-color); + padding: 1px; +} + +.newsfoot-footnote-popover-arrow { + background: var(--footnote-popover-background); + border: 1px solid var(--footnote-popover-border); +} + +.newsfoot-footnote-popover-inner { + background: var(--footnote-popover-background); +} + +body a.footnote, +body a.footnote:visited, +.newsfoot-footnote-popover + a.footnote:hover { + background: var(--footnote-color); + color: white; + transition: background-color 200ms ease-out; +} + +/* Overrides the .articleBody a underline */ +.articleBody a.footnote { + text-decoration: none; +} + +a.footnote:hover, +.newsfoot-footnote-popover + a.footnote { + background: var(--header-background); + transition: background-color 200ms ease-out; +} + +/* iOS Specific */ +@supports (-webkit-touch-callout: none) { + + body { + word-break: break-word; + -webkit-hyphens: auto; + -webkit-text-size-adjust: none; + } + + :root { + font-family: var(--body-font); + /* The font-size is replaced at runtime by the dynamic type size */ + font-size: [[font-size]]px; + } + + .fontSize { + font-family: var(--body-font); + font-size: [[font-size]]px; + } + + .articleContent, .barContent { + padding-left: 20px; + padding-right: 20px; + } +} + +/* macOS Specific */ +@supports not (-webkit-touch-callout: none) { + + body { + font-family: var(--body-font); + } + + .articleContent, .barContent { + padding-left: 48px; + padding-right: 48px; + } + + .smallText { + font-size: 15px; + } + + .mediumText { + font-size: 17px; + } + + .largeText { + font-size: 19px; + } + + .xlargeText { + font-size: 21px; + } + + .xxlargeText { + font-size: 23px; + } +} diff --git a/Themes/Plum.nnwtheme/template.html b/Themes/Plum.nnwtheme/template.html new file mode 100644 index 000000000..69f92406e --- /dev/null +++ b/Themes/Plum.nnwtheme/template.html @@ -0,0 +1,34 @@ +
    + + + + + +
    + +
    + [[title]] +
    + +
    +
    [[body]]
    +
    + + +
    + +
    diff --git a/Themes/Plum.nnwtheme/template7.3.html b/Themes/Plum.nnwtheme/template7.3.html new file mode 100644 index 000000000..d10389124 --- /dev/null +++ b/Themes/Plum.nnwtheme/template7.3.html @@ -0,0 +1,36 @@ +
    + + + + + +
    + +
    + [[title]] +
    + +
    + [[primary_media]] +
    [[body]]
    + [[enclosures]] +
    + + +
    + +
    diff --git a/Resources/Themes/Promenade.nnwtheme/template.html b/Themes/Promenade.nnwtheme/template7.3.html similarity index 98% rename from Resources/Themes/Promenade.nnwtheme/template.html rename to Themes/Promenade.nnwtheme/template7.3.html index b7c93560a..d34e21473 100644 --- a/Resources/Themes/Promenade.nnwtheme/template.html +++ b/Themes/Promenade.nnwtheme/template7.3.html @@ -42,7 +42,9 @@ body: The body of the article.
    diff --git a/Resources/Themes/Sepia.nnwtheme/template.html b/Themes/Sepia.nnwtheme/template7.3.html similarity index 95% rename from Resources/Themes/Sepia.nnwtheme/template.html rename to Themes/Sepia.nnwtheme/template7.3.html index d77e90199..ee737c2ea 100644 --- a/Resources/Themes/Sepia.nnwtheme/template.html +++ b/Themes/Sepia.nnwtheme/template7.3.html @@ -11,5 +11,7 @@ +[[primary_media]]
    [[body]]
    +[[enclosures]] diff --git a/Resources/Themes/Tiqoe Dark.nnwtheme/template.html b/Themes/Tiqoe Dark.nnwtheme/template7.3.html similarity index 95% rename from Resources/Themes/Tiqoe Dark.nnwtheme/template.html rename to Themes/Tiqoe Dark.nnwtheme/template7.3.html index db2639225..aca45c83c 100644 --- a/Resources/Themes/Tiqoe Dark.nnwtheme/template.html +++ b/Themes/Tiqoe Dark.nnwtheme/template7.3.html @@ -11,5 +11,7 @@ +[[primary_media]]
    [[body]]
    +[[enclosures]] \ No newline at end of file diff --git a/Resources/Themes/Verdana Revival.nnwtheme/template.html b/Themes/Verdana Revival.nnwtheme/template7.3.html similarity index 96% rename from Resources/Themes/Verdana Revival.nnwtheme/template.html rename to Themes/Verdana Revival.nnwtheme/template7.3.html index baf763f14..2f5a6e61a 100644 --- a/Resources/Themes/Verdana Revival.nnwtheme/template.html +++ b/Themes/Verdana Revival.nnwtheme/template7.3.html @@ -21,7 +21,9 @@
    + [[primary_media]]
    [[body]]
    + [[enclosures]]