Merge branch 'feature/image-resizing'

This commit is contained in:
Brent Simmons committed 2026-03-30 17:37:07 -07:00
commit 4574c525de
22 files changed
+137 -171

No files matched your search

+4
View File
@@ -782,6 +782,10 @@ extension AppDelegate {
}
}
@IBAction func openImageCacheFolder(_ sender: Any?) {
NSWorkspace.shared.open(AppConfig.cacheFolder)
}
@IBAction func showCloudKitStats(_ sender: Any?) {
if cloudKitStatsWindowController == nil {
cloudKitStatsWindowController = CloudKitStatsWindowController()
+7
View File
@@ -555,6 +555,13 @@
<action selector="vacuumDatabases:" target="Ady-hI-5gd" id="pQw-eT-j7Y"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="c4R-jH-7kP"/>
<menuItem title="Open Image Cache Folder" id="x9L-mW-2vQ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="openImageCacheFolder:" target="Ady-hI-5gd" id="bT3-nF-8wR"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
+71 -110
View File
@@ -7,6 +7,7 @@
//
import Foundation
import UniformTypeIdentifiers
import os
#if os(macOS)
@@ -20,7 +21,6 @@ public typealias RSImage = UIImage
#endif
private let RSImageLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "RSImage")
private let debugLoggingEnabled = false
public extension RSImage {
@@ -130,110 +130,12 @@ public extension RSImage {
}
}
/// Create a scaled image from image data.
///
/// - Note: the returned image may be larger than `maxPixelSize`, but not more than `maxPixelSize * 2`.
/// - Parameters:
/// - data: The data object containing the image data.
/// - maxPixelSize: The maximum dimension of the image.
static func scaleImage(_ data: Data, maxPixelSize: Int) -> CGImage? {
/// Scales image data down to maxPixelSize and returns the result as PNG Data.
/// 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.
static func scaledImageData(_ data: Data, maxPixelSize: Int) -> Data? {
guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else {
if debugLoggingEnabled {
RSImageLogger.debug("RSImageLogger: couldn’t create image source")
}
return nil
}
let numberOfImages = CGImageSourceGetCount(imageSource)
if debugLoggingEnabled {
RSImageLogger.debug("RSImageLogger: numberOfImages == \(numberOfImages, privacy: .public)")
}
guard numberOfImages > 0 else {
return nil
}
var exactMatch: (index: Int, maxDimension: Int)?
var goodMatch: (index: Int, maxDimension: Int)?
var smallMatch: (index: Int, maxDimension: Int)?
// Single pass through all images to find the best match
for i in 0..<numberOfImages {
guard let cfImageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
let imagePixelWidth = (cfImageProperties as NSDictionary)[kCGImagePropertyPixelWidth] as? NSNumber,
let imagePixelHeight = (cfImageProperties as NSDictionary)[kCGImagePropertyPixelHeight] as? NSNumber else {
continue
}
let width = imagePixelWidth.intValue
let height = imagePixelHeight.intValue
let maxDimension = max(width, height)
if debugLoggingEnabled {
RSImageLogger.debug("RSImageLogger: found width \(width, privacy: .public) height \(height, privacy: .public) \(maxPixelSize, privacy: .public)")
}
// Skip invalid dimensions
guard width > 0 && height > 0 else {
continue
}
// Check for exact match (largest dimension equals maxPixelSize)
if maxDimension == maxPixelSize {
exactMatch = (i, maxDimension)
if debugLoggingEnabled {
RSImageLogger.debug("RSImageLogger: found exact match for maxPixelSize: \(maxPixelSize, privacy: .public)")
}
break // Exact match is best, stop searching
}
// Check for good larger match
if maxDimension > maxPixelSize && maxDimension <= maxPixelSize * 4 {
if let currentGoodMatch = goodMatch {
if maxDimension < currentGoodMatch.maxDimension {
goodMatch = (i, maxDimension) // Prefer smaller size in this range
}
} else {
goodMatch = (i, maxDimension)
}
if debugLoggingEnabled {
RSImageLogger.debug("RSImageLogger: found good match \(maxDimension, privacy: .public) for maxPixelSize: \(maxPixelSize, privacy: .public)")
}
}
// Check for small match (smaller than maxPixelSize)
if maxDimension < maxPixelSize {
if let currentSmallMatch = smallMatch {
if maxDimension > currentSmallMatch.maxDimension {
smallMatch = (i, maxDimension) // Prefer larger size in this range
}
} else {
smallMatch = (i, maxDimension)
}
if debugLoggingEnabled {
RSImageLogger.debug("RSImageLogger: found small match \(maxDimension, privacy: .public) for maxPixelSize: \(maxPixelSize, privacy: .public)")
}
}
}
// Return best match in order of preference: exact > good > small
if let match = exactMatch ?? goodMatch ?? smallMatch {
return CGImageSourceCreateImageAtIndex(imageSource, match.index, nil)
}
// Fallback to creating a thumbnail
if debugLoggingEnabled {
RSImageLogger.debug("RSImageLogger: found no match — calling createThumbnail")
}
return RSImage.createThumbnail(imageSource, maxPixelSize: maxPixelSize)
}
/// Create a thumbnail from a CGImageSource.
///
/// - Parameters:
/// - imageSource: The `CGImageSource` from which to create the thumbnail.
/// - maxPixelSize: The maximum dimension of the resulting image.
static func createThumbnail(_ imageSource: CGImageSource, maxPixelSize: Int) -> CGImage? {
guard maxPixelSize > 0 else {
return nil
}
@@ -242,13 +144,72 @@ public extension RSImage {
return nil
}
if debugLoggingEnabled {
RSImageLogger.debug("RSImageLogger: createThumbnail image source count = \(count, privacy: .public)")
// Find the largest frame in the image source.
var largestIndex = 0
var largestWidth = 0
var largestHeight = 0
var largestMaxDimension = 0
for i in 0..<count {
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) as NSDictionary?,
let width = properties[kCGImagePropertyPixelWidth] as? Int,
let height = properties[kCGImagePropertyPixelHeight] as? Int else {
continue
}
let maxDimension = max(width, height)
if maxDimension > largestMaxDimension {
largestIndex = i
largestWidth = width
largestHeight = height
largestMaxDimension = maxDimension
}
}
let options = [kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
kCGImageSourceThumbnailMaxPixelSize: NSNumber(value: maxPixelSize)]
return CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary)
guard largestMaxDimension > 0 else {
return nil
}
let needsResize = largestMaxDimension > maxPixelSize
let isMultiImage = count > 1
// Single-frame image already small enough — return original data as-is.
if !needsResize && !isMultiImage {
RSImageLogger.info("Image already small enough: \(largestWidth, privacy: .public)x\(largestHeight, privacy: .public) <= \(maxPixelSize, privacy: .public)px max")
return data
}
// Either too large or multi-image — extract/resize to a single PNG.
let cgImage: CGImage?
if needsResize {
let options: [CFString: Any] = [
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
kCGImageSourceThumbnailMaxPixelSize: maxPixelSize
]
cgImage = CGImageSourceCreateThumbnailAtIndex(imageSource, largestIndex, options as CFDictionary)
} else {
cgImage = CGImageSourceCreateImageAtIndex(imageSource, largestIndex, nil)
}
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 {
return nil
}
if needsResize {
RSImageLogger.info("Resized image from \(largestWidth, privacy: .public)x\(largestHeight, privacy: .public) to \(cgImage.width, privacy: .public)x\(cgImage.height, privacy: .public)")
} else {
RSImageLogger.info("Extracted largest frame (\(largestWidth, privacy: .public)x\(largestHeight, privacy: .public)) from multi-image source (\(count, privacy: .public) frames)")
}
return mutableData as Data
}
}
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
+1 -1
View File
@@ -918,7 +918,7 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1240;
LastUpgradeCheck = 2630;
LastUpgradeCheck = 2640;
ORGANIZATIONNAME = "Ranchero Software";
TargetAttributes = {
176813F22564BB2C00D98635 = {
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
wasCreatedForAppExtension = "YES"
version = "2.0">
<BuildAction
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
LastUpgradeVersion = "2640"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
+33
View File
@@ -14,8 +14,12 @@ struct CacheCleaner {
static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "CacheCleaner")
private static let didPurgeImageCachesForResizingKey = "didPurgeImageCachesForResizing-2026-03-30"
static func purgeIfNecessary() {
purgeImageCachesForResizingIfNeeded()
guard let flushDate = AppDefaults.shared.lastImageCacheFlushDate else {
AppDefaults.shared.lastImageCacheFlushDate = Date()
return
@@ -46,3 +50,32 @@ struct CacheCleaner {
}
}
}
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 {
return
}
let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
let foldersToRemove = [
cacheDir.appendingPathComponent("Favicons"),
cacheDir.appendingPathComponent("Images"),
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
}
}
UserDefaults.standard.set(true, forKey: didPurgeImageCachesForResizingKey)
}
}
+1 -42
View File
@@ -14,25 +14,7 @@ import UIKit
#endif
extension RSImage {
static let maxIconSize = 48
static func scaledForIcon(_ data: Data, imageResultBlock: @escaping ImageResultBlock) {
IconScalerQueue.shared.scaledForIcon(data, imageResultBlock)
}
static func scaledForIcon(_ data: Data) -> RSImage? {
let scaledMaxPixelSize = Int(ceil(CGFloat(RSImage.maxIconSize) * RSScreen.maxScreenScale))
guard var cgImage = RSImage.scaleImage(data, maxPixelSize: scaledMaxPixelSize) else {
return nil
}
#if os(iOS)
return RSImage(cgImage: cgImage)
#else
let size = NSSize(width: cgImage.width, height: cgImage.height)
return RSImage(cgImage: cgImage, size: size)
#endif
}
static let maxIconPixelSize = Int(ceil(48.0 * RSScreen.maxScreenScale))
static var appIconImage: RSImage? {
#if os(macOS)
@@ -60,26 +42,3 @@ extension IconImage {
static let nnwFeedIcon = IconImage(Assets.Images.nnwFeedIcon)
}
// MARK: - IconScalerQueue
private final class IconScalerQueue: Sendable {
static let shared = IconScalerQueue()
private let queue: DispatchQueue = {
let q = DispatchQueue(label: "IconScaler", attributes: .initiallyInactive)
q.setTarget(queue: DispatchQueue.global(qos: .default))
q.activate()
return q
}()
func scaledForIcon(_ data: Data, _ imageResultBlock: @escaping ImageResultBlock) {
queue.async {
let image = RSImage.scaledForIcon(data)
DispatchQueue.main.async {
imageResultBlock(image)
}
}
}
}
@@ -135,8 +135,9 @@ private extension SingleFaviconDownloader {
do {
let (data, response) = try await Downloader.shared.download(url)
if let data, !data.isEmpty, let response, response.statusIsOK {
saveToDisk(data)
let image = await RSImage.image(data: data)
let scaledData = RSImage.scaledImageData(data, maxPixelSize: RSImage.maxIconPixelSize) ?? data
saveToDisk(scaledData)
let image = await RSImage.image(data: scaledData)
return image
}
+1 -1
View File
@@ -66,7 +66,7 @@ extension Notification.Name {
@MainActor private extension AuthorAvatarDownloader {
func scaleAndCacheImageData(_ imageData: Data, _ avatarURL: String) {
RSImage.scaledForIcon(imageData) { (image) in
RSImage.image(with: imageData) { (image) in
MainActor.assumeIsolated {
if let image {
self.handleImageDidBecomeAvailable(avatarURL, image)
+1 -1
View File
@@ -181,7 +181,7 @@ private extension FeedIconDownloader {
imageResultBlock(nil)
return
}
RSImage.scaledForIcon(imageData, imageResultBlock: imageResultBlock)
RSImage.image(with: imageData, imageResultBlock: imageResultBlock)
}
func postFeedIconDidBecomeAvailableNotification(_ feed: Feed) {
+3 -2
View File
@@ -116,8 +116,9 @@ private extension ImageDownloader {
let (data, response) = try await Downloader.shared.download(imageURL)
if let data, !data.isEmpty, let response, response.statusIsOK {
saveToDisk(url, data)
return data
let scaledData = RSImage.scaledImageData(data, maxPixelSize: RSImage.maxIconPixelSize) ?? data
saveToDisk(url, scaledData)
return scaledData
}
if let response = response as? HTTPURLResponse, response.statusCode >= HTTPResponseCode.badRequest && response.statusCode <= HTTPResponseCode.notAcceptable {