Merge branch 'bug/state-restoration-4830' into release/6.2.1

This commit is contained in:
Brent Simmons committed 2025-12-03 20:12:39 -08:00
commit f4f6655f6d
17 files changed
+5203 -243

No files matched your search

+3
View File
@@ -74,3 +74,6 @@ Guard statements should always put the return in a separate line.
Don’t do force unwrapping of optionals.
## Things to Know
Just because unit tests pass doesn’t mean a given bug is fixed. It may not have a test. It may not even be testable — it may require manual testing.
@@ -143,7 +143,7 @@ protocol SidebarDelegate: AnyObject {
expandedTable = Set(containerIdentifiers)
}
guard let selectedFeedsState = state[UserInfoKey.selectedFeedsState] as? [[AnyHashable: AnyHashable]] else {
guard let selectedFeedsState = state[UserInfoKey.selectedFeedsState] as? [[String: String]] else {
return
}
@@ -28,7 +28,15 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
@IBOutlet var tableView: TimelineTableView!
private var readFilterEnabledTable = [FeedIdentifier: Bool]()
private var feedsHidingReadArticles = Set<FeedIdentifier>()
private var readFilterEnabledTable: [FeedIdentifier: Bool] {
var d = [FeedIdentifier: Bool]()
for feedIdentifier in feedsHidingReadArticles {
d[feedIdentifier] = true
}
return d
}
var isReadFiltered: Bool? {
guard representedObjects?.count == 1, let timelineFeed = representedObjects?.first as? Feed else {
return nil
@@ -36,8 +44,8 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
guard timelineFeed.defaultReadFilterType != .alwaysRead else {
return nil
}
if let feedID = timelineFeed.feedID, let readFilterEnabled = readFilterEnabledTable[feedID] {
return readFilterEnabled
if let feedID = timelineFeed.feedID {
return feedsHidingReadArticles.contains(feedID)
} else {
return timelineFeed.defaultReadFilterType == .read
}
@@ -81,7 +89,7 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
}
var windowState: TimelineWindowState {
let readArticlesFilterStateKeys = readFilterEnabledTable.keys.compactMap { $0.userInfo as? [String: String] }
let readArticlesFilterStateKeys = readFilterEnabledTable.keys.compactMap { $0.userInfo }
let readArticlesFilterStateValues = readFilterEnabledTable.values.compactMap( { $0 })
if selectedArticles.count == 1 {
@@ -284,17 +292,34 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
func toggleReadFilter() {
guard let filter = isReadFiltered, let feedID = (representedObjects?.first as? Feed)?.feedID else { return }
readFilterEnabledTable[feedID] = !filter
if filter {
noteFeedHidesReadArticles(feedID)
} else {
noteFeedShowsReadArticles(feedID)
}
delegate?.timelineInvalidatedRestorationState(self)
fetchAndReplacePreservingSelection()
}
// MARK: State Restoration
private func noteFeedHidesReadArticles(_ feedID: FeedIdentifier) {
feedsHidingReadArticles.insert(feedID)
}
private func noteFeedShowsReadArticles(_ feedID: FeedIdentifier) {
feedsHidingReadArticles.remove(feedID)
}
func restoreState(from state: TimelineWindowState) {
for i in 0..<state.readArticlesFilterStateKeys.count {
if let feedIdentifier = FeedIdentifier(userInfo: state.readArticlesFilterStateKeys[i]) {
readFilterEnabledTable[feedIdentifier] = state.readArticlesFilterStateValues[i]
let hidesReadFeeds = state.readArticlesFilterStateValues[i]
if hidesReadFeeds {
noteFeedHidesReadArticles(feedIdentifier)
} else {
noteFeedShowsReadArticles(feedIdentifier)
}
}
}
@@ -321,14 +346,19 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr
///
/// TODO: Delete for NetNewsWire 7.
func restoreLegacyState(from state: [AnyHashable: Any]) {
guard let readArticlesFilterStateKeys = state[UserInfoKey.readArticlesFilterStateKeys] as? [[AnyHashable: AnyHashable]],
guard let readArticlesFilterStateKeys = state[UserInfoKey.readArticlesFilterStateKeys] as? [[String: String]],
let readArticlesFilterStateValues = state[UserInfoKey.readArticlesFilterStateValues] as? [Bool] else {
return
}
for i in 0..<readArticlesFilterStateKeys.count {
if let feedIdentifier = FeedIdentifier(userInfo: readArticlesFilterStateKeys[i]) {
readFilterEnabledTable[feedIdentifier] = readArticlesFilterStateValues[i]
let hidesReadArticles = readArticlesFilterStateValues[i]
if hidesReadArticles {
noteFeedHidesReadArticles(feedIdentifier)
} else {
noteFeedShowsReadArticles(feedIdentifier)
}
}
}
@@ -398,6 +398,23 @@ public final class AccountManager: UnreadCountProvider {
}
}
/// Fetch a single article by accountID and articleID.
/// Returns nil if the account or article is not found.
public func fetchArticle(accountID: String, articleID: String) -> Article? {
precondition(Thread.isMainThread)
guard let account = existingAccount(with: accountID) else {
return nil
}
do {
let articles = try account.fetchArticles(.articleIDs(Set([articleID])))
return articles.first
} catch {
return nil
}
}
// MARK: - Fetching Article Counts
public func fetchCountForStarredArticles() throws -> Int {
@@ -13,71 +13,100 @@ public protocol FeedIdentifiable {
}
public enum FeedIdentifier: CustomStringConvertible, Hashable, Equatable {
case smartFeed(String) // String is a unique identifier
case script(String) // String is a unique identifier
case webFeed(String, String) // accountID, webFeedID
case folder(String, String) // accountID, folderName
public var description: String {
switch self {
case .smartFeed(let id):
return "smartFeed: \(id)"
case .script(let id):
return "script: \(id)"
case .webFeed(let accountID, let webFeedID):
return "feed: \(accountID)_\(webFeedID)"
case .folder(let accountID, let folderName):
return "folder: \(accountID)_\(folderName)"
}
private struct TypeName {
static let smartFeed = "smartFeed"
static let script = "script"
static let feed = "feed"
static let folder = "folder"
}
public var userInfo: [AnyHashable: AnyHashable] {
switch self {
case .smartFeed(let id):
return [
"type": "smartFeed",
"id": id
]
case .script(let id):
return [
"type": "script",
"id": id
]
case .webFeed(let accountID, let webFeedID):
return [
"type": "feed",
"accountID": accountID,
"webFeedID": webFeedID
]
case .folder(let accountID, let folderName):
return [
"type": "folder",
"accountID": accountID,
"folderName": folderName
]
}
private struct Key {
static let typeName = "type"
static let id = "id"
static let accountID = "accountID"
static let feedID = "webFeedID"
static let folderName = "folderName"
}
public init?(userInfo: [AnyHashable: AnyHashable]) {
guard let type = userInfo["type"] as? String else { return nil }
switch type {
case "smartFeed":
guard let id = userInfo["id"] as? String else { return nil }
self = FeedIdentifier.smartFeed(id)
case "script":
guard let id = userInfo["id"] as? String else { return nil }
self = FeedIdentifier.script(id)
case "feed":
guard let accountID = userInfo["accountID"] as? String, let webFeedID = userInfo["webFeedID"] as? String else { return nil }
self = FeedIdentifier.webFeed(accountID, webFeedID)
case "folder":
guard let accountID = userInfo["accountID"] as? String, let folderName = userInfo["folderName"] as? String else { return nil }
self = FeedIdentifier.folder(accountID, folderName)
default:
return nil
private var typeName: String {
switch self {
case .smartFeed:
return TypeName.smartFeed
case .script:
return TypeName.script
case .webFeed:
return TypeName.feed
case .folder:
return TypeName.folder
}
}
public var description: String {
switch self {
case .smartFeed(let id):
return "\(typeName): \(id)"
case .script(let id):
return "\(typeName): \(id)"
case .webFeed(let accountID, let webFeedID):
return "\(typeName): \(accountID)_\(webFeedID)"
case .folder(let accountID, let folderName):
return "\(typeName): \(accountID)_\(folderName)"
}
}
public var userInfo: [String: String] {
var d = [Key.typeName: typeName]
switch self {
case .smartFeed(let id):
d[Key.id] = id
case .script(let id):
d[Key.id] = id
case .webFeed(let accountID, let webFeedID):
d[Key.accountID] = accountID
d[Key.feedID] = webFeedID
case .folder(let accountID, let folderName):
d[Key.accountID] = accountID
d[Key.folderName] = folderName
}
return d
}
public init?(userInfo: [String: String]) {
guard let type = userInfo[Key.typeName] else {
return nil
}
switch type {
case TypeName.smartFeed:
guard let id = userInfo[Key.id] else {
return nil
}
self = FeedIdentifier.smartFeed(id)
case TypeName.script:
guard let id = userInfo[Key.id] else {
return nil
}
self = FeedIdentifier.script(id)
case TypeName.feed:
guard let accountID = userInfo[Key.accountID], let webFeedID = userInfo[Key.feedID] else {
return nil
}
self = FeedIdentifier.webFeed(accountID, webFeedID)
case TypeName.folder:
guard let accountID = userInfo[Key.accountID], let folderName = userInfo[Key.folderName] else {
return nil
}
self = FeedIdentifier.folder(accountID, folderName)
default:
assertionFailure("Expected valid FeedIdentifier.userInfo but got \(userInfo)")
return nil
}
}
}
+2
View File
@@ -430,6 +430,7 @@
84D35E0C2DB9F32D004AA60E /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
ArticleSpecifier.swift,
Extensions/IconImage.swift,
"Extensions/Node-Extensions.swift",
ShareExtension/ExtensionContainers.swift,
@@ -438,6 +439,7 @@
ShareExtension/ExtensionFeedAddRequestFile.swift,
ShareExtension/SafariExt.js,
ShareExtension/ShareDefaultContainer.swift,
UserInfoKey.swift,
);
target = 513C5CE5232571C2003D4054 /* NetNewsWire iOS Share Extension */;
};
+3 -8
View File
@@ -23,14 +23,9 @@ final class ActivityManager {
private var readingArticle: Article?
var stateRestorationActivity: NSUserActivity {
if let activity = readingActivity {
return activity
}
if let activity = selectingActivity {
return activity
}
// State restoration is now handled via UserDefaults (AppDefaults.selectedSidebarItem and AppDefaults.selectedArticle).
// The reading/selecting activities are still maintained for Handoff, Spotlight, and Siri Shortcuts,
// but we don't use them for same-device state restoration anymore.
let activity = NSUserActivity(activityType: ActivityType.restoration.rawValue)
#if os(iOS)
activity.persistentIdentifier = UUID().uuidString
+48
View File
@@ -0,0 +1,48 @@
//
// ArticleSpecifier.swift
// Articles
//
// Created by Brent Simmons on 12/1/25.
//
import Foundation
import Articles
/// Use this to refer to an Article when you can look it up.
///
/// For instance, this can be saved to disk as part of state restoration.
struct ArticleSpecifier: Hashable, Sendable {
let accountID: String
let articleID: String
private struct Key {
static let accountID = "accountID"
static let articleID = "articleID"
}
/// Plist-compatible dictionary, meant to be saved to disk or in UserDefaults.
var dictionary: [String: String] {
[Key.accountID: accountID, Key.articleID: articleID]
}
init(accountID: String, articleID: String) {
self.accountID = accountID
self.articleID = articleID
}
init?(dictionary: [String: String]) {
guard let accountID = dictionary[Key.accountID],
let articleID = dictionary[Key.articleID] else {
return nil
}
self.init(accountID: accountID, articleID: articleID)
}
init(article: Article) {
self.init(accountID: article.accountID, articleID: article.articleID)
}
func matchesArticle(_ article: Article) -> Bool {
article.accountID == accountID && article.articleID == articleID
}
}
+4
View File
@@ -20,6 +20,10 @@ extension Array where Element == Article {
return self[row]
}
func article(matching articleSpecifier: ArticleSpecifier) -> Article? {
first { articleSpecifier.matchesArticle($0) }
}
func orderedRowIndexes(fromIndex startIndex: Int, wrappingToTop wrapping: Bool) -> [Int] {
if startIndex >= self.count {
// Wrap around to the top if specified
+181 -23
View File
@@ -7,6 +7,9 @@
//
import UIKit
import os.log
import Account
import Articles
enum UserInterfaceColorPalette: Int, CustomStringConvertible, CaseIterable {
case automatic = 0
@@ -23,7 +26,6 @@ enum UserInterfaceColorPalette: Int, CustomStringConvertible, CaseIterable {
return NSLocalizedString("Dark", comment: "Dark")
}
}
}
extension Notification.Name {
@@ -31,10 +33,11 @@ extension Notification.Name {
}
final class AppDefaults {
static let shared = AppDefaults()
static let defaultThemeName = "Default"
static let shared = AppDefaults()
fileprivate static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AppDefaults")
private init() {}
static var store: UserDefaults = {
@@ -65,8 +68,11 @@ final class AppDefaults {
static let hideReadFeeds = "hideReadFeeds"
static let isShowingExtractedArticle = "isShowingExtractedArticle"
static let articleWindowScrollY = "articleWindowScrollY"
static let containerExpandedWindowState = "containerExpandedWindowState"
static let readArticlesFilterState = "readArticlesFilterState"
static let expandedContainers = "expandedContainers"
static let sidebarItemsHidingReadArticles = "sidebarItemsHidingReadArticles"
static let selectedSidebarItem = "selectedSidebarItem"
static let selectedArticle = "selectedArticle"
static let didMigrateLegacyStateRestorationInfo = "didMigrateLegacyStateRestorationInfo"
}
let isDeveloperBuild: Bool = {
@@ -246,10 +252,6 @@ final class AppDefaults {
}
}
var hideReadFeedsHasBeenSet: Bool {
UserDefaults.standard.object(forKey: Key.hideReadFeeds) != nil
}
var hideReadFeeds: Bool {
get {
UserDefaults.standard.bool(forKey: Key.hideReadFeeds)
@@ -259,10 +261,6 @@ final class AppDefaults {
}
}
var isShowingExtractedArticleHasBeenSet: Bool {
UserDefaults.standard.object(forKey: Key.isShowingExtractedArticle) != nil
}
var isShowingExtractedArticle: Bool {
get {
UserDefaults.standard.bool(forKey: Key.isShowingExtractedArticle)
@@ -272,10 +270,6 @@ final class AppDefaults {
}
}
var articleWindowScrollYHasBeenSet: Bool {
UserDefaults.standard.object(forKey: Key.articleWindowScrollY) != nil
}
var articleWindowScrollY: Int {
get {
UserDefaults.standard.integer(forKey: Key.articleWindowScrollY)
@@ -285,21 +279,73 @@ final class AppDefaults {
}
}
var containerExpandedWindowState: [[String: String]]? {
var expandedContainers: Set<ContainerIdentifier> {
get {
UserDefaults.standard.array(forKey: Key.containerExpandedWindowState) as? [[String: String]]
guard let rawIdentifiers = UserDefaults.standard.array(forKey: Key.expandedContainers) as? [[String: String]] else {
return Set<ContainerIdentifier>()
}
let containerIdentifiers = rawIdentifiers.compactMap { ContainerIdentifier(userInfo: $0) }
return Set(containerIdentifiers)
}
set {
UserDefaults.standard.set(newValue, forKey: Key.containerExpandedWindowState)
Self.logger.debug("AppDefaults: set expandedContainers: \(newValue)")
let containerIdentifierUserInfos = newValue.compactMap { $0.userInfo }
UserDefaults.standard.set(containerIdentifierUserInfos, forKey: Key.expandedContainers)
}
}
var readArticlesFilterState: [[String: String]]? {
var sidebarItemsHidingReadArticles: Set<FeedIdentifier> {
get {
UserDefaults.standard.array(forKey: Key.readArticlesFilterState) as? [[String: String]]
guard let rawIdentifiers = UserDefaults.standard.array(forKey: Key.sidebarItemsHidingReadArticles) as? [[String: String]] else {
return Set<FeedIdentifier>()
}
let feedIdentifiers = rawIdentifiers.compactMap { FeedIdentifier(userInfo: $0) }
return Set(feedIdentifiers)
}
set {
UserDefaults.standard.set(newValue, forKey: Key.readArticlesFilterState)
let feedIdentifierUserInfos = newValue.compactMap { $0.userInfo }
UserDefaults.standard.set(feedIdentifierUserInfos, forKey: Key.sidebarItemsHidingReadArticles)
}
}
var selectedSidebarItem: FeedIdentifier? {
get {
guard let userInfo = UserDefaults.standard.dictionary(forKey: Key.selectedSidebarItem) as? [String: String] else {
return nil
}
return FeedIdentifier(userInfo: userInfo)
}
set {
guard let newValue else {
UserDefaults.standard.removeObject(forKey: Key.selectedSidebarItem)
return
}
UserDefaults.standard.set(newValue.userInfo, forKey: Key.selectedSidebarItem)
}
}
var selectedArticle: ArticleSpecifier? {
get {
guard let d = UserDefaults.standard.dictionary(forKey: Key.selectedArticle) as? [String: String] else {
return nil
}
return ArticleSpecifier(dictionary: d)
}
set {
guard let newValue else {
UserDefaults.standard.removeObject(forKey: Key.selectedArticle)
return
}
UserDefaults.standard.set(newValue.dictionary, forKey: Key.selectedArticle)
}
}
var didMigrateLegacyStateRestorationInfo: Bool {
get {
UserDefaults.standard.bool(forKey: Key.didMigrateLegacyStateRestorationInfo)
}
set {
UserDefaults.standard.set(newValue, forKey: Key.didMigrateLegacyStateRestorationInfo)
}
}
@@ -380,3 +426,115 @@ private extension AppDefaults {
}
}
}
struct StateRestorationInfo {
let hideReadFeeds: Bool
let expandedContainers: Set<ContainerIdentifier>
let selectedSidebarItem: FeedIdentifier?
let sidebarItemsHidingReadArticles: Set<FeedIdentifier>
let selectedArticle: ArticleSpecifier?
let articleWindowScrollY: Int
let isShowingExtractedArticle: Bool
init(hideReadFeeds: Bool,
expandedContainers: Set<ContainerIdentifier>,
selectedSidebarItem: FeedIdentifier?,
sidebarItemsHidingReadArticles: Set<FeedIdentifier>,
selectedArticle: ArticleSpecifier?,
articleWindowScrollY: Int,
isShowingExtractedArticle: Bool) {
self.hideReadFeeds = hideReadFeeds
self.expandedContainers = expandedContainers
self.selectedSidebarItem = selectedSidebarItem
self.sidebarItemsHidingReadArticles = sidebarItemsHidingReadArticles
self.selectedArticle = selectedArticle
self.articleWindowScrollY = articleWindowScrollY
self.isShowingExtractedArticle = isShowingExtractedArticle
AppDefaults.logger.debug("AppDefaults: StateRestorationInfo:\nexpandedContainers: \(expandedContainers)\nselectedSidebarItem: \(selectedSidebarItem?.userInfo ?? [String: String]())\nsidebarItemsHidingReadArticles: \(sidebarItemsHidingReadArticles)\nselectedArticle: \(selectedArticle?.dictionary ?? [String: String]())\narticleWindowScrollY: \(articleWindowScrollY)\nisShowingExtractedArticle: \(isShowingExtractedArticle ? "true" : "false")")
}
init() {
self.init(hideReadFeeds: AppDefaults.shared.hideReadFeeds,
expandedContainers: AppDefaults.shared.expandedContainers,
selectedSidebarItem: AppDefaults.shared.selectedSidebarItem,
sidebarItemsHidingReadArticles: AppDefaults.shared.sidebarItemsHidingReadArticles,
selectedArticle: AppDefaults.shared.selectedArticle,
articleWindowScrollY: AppDefaults.shared.articleWindowScrollY,
isShowingExtractedArticle: AppDefaults.shared.isShowingExtractedArticle)
}
// TODO: Delete for NetNewsWire 7.1.
init(legacyState: NSUserActivity?) {
if AppDefaults.shared.didMigrateLegacyStateRestorationInfo {
self.init()
return
}
AppDefaults.shared.didMigrateLegacyStateRestorationInfo = true
// Extract legacy window state if available
guard let windowState = legacyState?.userInfo?[UserInfoKey.windowState] as? [AnyHashable: Any] else {
self.init()
return
}
let hideReadFeeds: Bool
if let legacyValue = windowState[UserInfoKey.readFeedsFilterState] as? Bool {
hideReadFeeds = legacyValue
} else {
hideReadFeeds = AppDefaults.shared.hideReadFeeds
}
let expandedContainers: Set<ContainerIdentifier>
if let legacyState = windowState[UserInfoKey.containerExpandedWindowState] as? [[AnyHashable: AnyHashable]] {
let convertedState = legacyState.compactMap { dict -> [String: String]? in
var stringDict = [String: String]()
for (key, value) in dict {
if let keyString = key as? String, let valueString = value as? String {
stringDict[keyString] = valueString
}
}
return stringDict.isEmpty ? nil : stringDict
}
let containerIdentifiers = convertedState.compactMap { ContainerIdentifier(userInfo: $0) }
expandedContainers = Set(containerIdentifiers)
} else {
expandedContainers = AppDefaults.shared.expandedContainers
}
let sidebarItemsHidingReadArticles: Set<FeedIdentifier>
if let legacyState = windowState[UserInfoKey.readArticlesFilterState] as? [[AnyHashable: AnyHashable]: Bool] {
let enabledFeeds = legacyState.filter { $0.value == true }
let convertedState = enabledFeeds.keys.compactMap { key -> [String: String]? in
var stringDict = [String: String]()
for (k, v) in key {
if let keyString = k as? String, let valueString = v as? String {
stringDict[keyString] = valueString
}
}
return stringDict.isEmpty ? nil : stringDict
}
let feedIdentifiers = convertedState.compactMap { FeedIdentifier(userInfo: $0) }
sidebarItemsHidingReadArticles = Set(feedIdentifiers)
} else {
sidebarItemsHidingReadArticles = AppDefaults.shared.sidebarItemsHidingReadArticles
}
let selectedSidebarItem: FeedIdentifier?
if let legacyState = windowState[UserInfoKey.feedIdentifier] as? [String: String],
let feedIdentifier = FeedIdentifier(userInfo: legacyState) {
selectedSidebarItem = feedIdentifier
} else {
selectedSidebarItem = AppDefaults.shared.selectedSidebarItem
}
self.init(hideReadFeeds: hideReadFeeds,
expandedContainers: expandedContainers,
selectedSidebarItem: selectedSidebarItem,
sidebarItemsHidingReadArticles: sidebarItemsHidingReadArticles,
selectedArticle: AppDefaults.shared.selectedArticle,
articleWindowScrollY: AppDefaults.shared.articleWindowScrollY,
isShowingExtractedArticle: AppDefaults.shared.isShowingExtractedArticle)
}
}
+109 -137
View File
@@ -62,13 +62,20 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
private let fetchRequestQueue = FetchRequestQueue()
// Which Containers are expanded
private var expandedTable = Set<ContainerIdentifier>()
private var expandedContainers = Set<ContainerIdentifier>()
// Which Containers used to be expanded. Reset by rebuilding the Shadow Table.
private var lastExpandedTable = Set<ContainerIdentifier>()
private var lastExpandedContainers = Set<ContainerIdentifier>()
// Which Feeds have the Read Articles Filter enabled
private var readFilterEnabledTable = [FeedIdentifier: Bool]()
private var feedsHidingReadArticles = Set<FeedIdentifier>()
private var readFilterEnabledTable: [FeedIdentifier: Bool] { // TODO: remove this
var d = [FeedIdentifier: Bool]()
for feedIdentifier in feedsHidingReadArticles {
d[feedIdentifier] = true
}
return d
}
// Flattened tree structure for the Sidebar
private var shadowTable = [(sectionID: String, feedNodes: [FeedNode])]()
@@ -119,11 +126,10 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
}
var isReadArticlesFiltered: Bool {
if let feedID = timelineFeed?.feedID, let readFilterEnabled = readFilterEnabledTable[feedID] {
return readFilterEnabled
} else {
return timelineDefaultReadFilterType != .none
if let feedID = timelineFeed?.feedID {
return feedsHidingReadArticles.contains(feedID)
}
return timelineDefaultReadFilterType != .none
}
var timelineDefaultReadFilterType: ReadFilterType {
@@ -231,7 +237,15 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
return nil
}
var currentArticle: Article?
var currentArticle: Article? {
didSet {
if let article = currentArticle {
AppDefaults.shared.selectedArticle = ArticleSpecifier(article: article)
} else {
AppDefaults.shared.selectedArticle = nil
}
}
}
private(set) var articles = ArticleArray() {
didSet {
@@ -282,8 +296,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
self.articleViewController?.coordinator = self
self.articleViewController?.navigationController?.delegate = self
for sectionNode in treeController.rootNode.childNodes {
markExpanded(sectionNode)
for _ in treeController.rootNode.childNodes {
shadowTable.append((sectionID: "", feedNodes: [FeedNode]()))
}
@@ -304,87 +317,61 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
NotificationCenter.default.addObserver(self, selector: #selector(themeDownloadDidFail(_:)), name: .didFailToImportThemeWithError, object: nil)
}
func restoreWindowState(_ activity: NSUserActivity?) {
migrateFromLegacyStateStorage(activity)
restoreWindowStateFromUserDefaults()
func restoreWindowState(activity: NSUserActivity?) {
let stateInfo = StateRestorationInfo(legacyState: activity)
restoreWindowState(stateInfo)
}
/// Copy storage from legacy scene restoration state to UserDefaults.
///
/// We can do this because we support just one scene now.
/// The idea is to make state restoration more reliable.
private func migrateFromLegacyStateStorage(_ activity: NSUserActivity?) {
guard let windowState = activity?.userInfo?[UserInfoKey.windowState] as? [AnyHashable: Any] else {
return
}
// containerExpandedWindowState
if AppDefaults.shared.containerExpandedWindowState == nil,
let legacyState = windowState[UserInfoKey.containerExpandedWindowState] as? [[AnyHashable: AnyHashable]] {
let convertedState = legacyState.compactMap { dict -> [String: String]? in
var stringDict = [String: String]()
for (key, value) in dict {
if let keyString = key as? String, let valueString = value as? String {
stringDict[keyString] = valueString
}
}
return stringDict.isEmpty ? nil : stringDict
private func restoreWindowState(_ stateInfo: StateRestorationInfo) {
if AppDefaults.shared.isFirstRun {
// Expand top-level items on first run.
for sectionNode in treeController.rootNode.childNodes {
markExpanded(sectionNode)
}
AppDefaults.shared.containerExpandedWindowState = convertedState
saveExpandedContainersToUserDefaults()
} else {
expandedContainers = stateInfo.expandedContainers
}
// readArticlesFilterState
if AppDefaults.shared.readArticlesFilterState == nil,
let legacyState = windowState[UserInfoKey.readArticlesFilterState] as? [[AnyHashable: AnyHashable]: Bool] {
let enabledFeeds = legacyState.filter { $0.value == true }
let convertedState = enabledFeeds.keys.compactMap { key -> [String: String]? in
var stringDict = [String: String]()
for (k, v) in key {
if let keyString = k as? String, let valueString = v as? String {
stringDict[keyString] = valueString
}
}
return stringDict.isEmpty ? nil : stringDict
}
AppDefaults.shared.readArticlesFilterState = convertedState
}
// hideReadFeeds
if !AppDefaults.shared.hideReadFeedsHasBeenSet,
let legacyState = windowState[UserInfoKey.readFeedsFilterState] as? Bool {
AppDefaults.shared.hideReadFeeds = legacyState
}
// isShowingExtractedArticle
if !AppDefaults.shared.isShowingExtractedArticleHasBeenSet,
let legacyState = windowState[UserInfoKey.isShowingExtractedArticle] as? Bool {
AppDefaults.shared.isShowingExtractedArticle = legacyState
}
// articleWindowScrollY
if !AppDefaults.shared.articleWindowScrollYHasBeenSet,
let legacyState = windowState[UserInfoKey.articleWindowScrollY] as? Int {
AppDefaults.shared.articleWindowScrollY = legacyState
}
}
private func restoreWindowStateFromUserDefaults() {
// Restore containerExpandedWindowState from UserDefaults
if let storedState = AppDefaults.shared.containerExpandedWindowState {
let containerIdentifiers = storedState.compactMap { ContainerIdentifier(userInfo: $0) }
expandedTable = Set(containerIdentifiers)
}
// Restore readArticlesFilterState from UserDefaults
restoreReadFilterEnabledTableFromUserDefaults()
feedsHidingReadArticles.formUnion(stateInfo.sidebarItemsHidingReadArticles)
rebuildBackingStores(initialLoad: true)
// You can't assign the Feeds Read Filter until we've built the backing stores at least once or there is nothing
// for state restoration to work with while we are waiting for the unread counts to initialize.
treeControllerDelegate.isReadFiltered = AppDefaults.shared.hideReadFeeds
treeControllerDelegate.isReadFiltered = stateInfo.hideReadFeeds
restoreSelectedSidebarItemAndArticle(stateInfo)
}
private func restoreSelectedSidebarItemAndArticle(_ stateInfo: StateRestorationInfo) {
guard let selectedSidebarItem = stateInfo.selectedSidebarItem else {
return
}
guard let feedNode = nodeFor(feedID: selectedSidebarItem),
let indexPath = indexPathFor(feedNode) else {
return
}
selectFeed(indexPath: indexPath, animations: []) {
self.restoreSelectedArticle(stateInfo)
}
}
private func restoreSelectedArticle(_ stateInfo: StateRestorationInfo) {
guard let articleSpecifier = stateInfo.selectedArticle else {
return
}
let article = articles.article(matching: articleSpecifier) ??
AccountManager.shared.fetchArticle(accountID: articleSpecifier.accountID,
articleID: articleSpecifier.articleID)
if let article {
selectArticle(article, isShowingExtractedArticle: stateInfo.isShowingExtractedArticle, articleWindowScrollY: stateInfo.articleWindowScrollY)
}
}
func handle(_ activity: NSUserActivity) {
selectFeed(indexPath: nil) {
guard let activityType = ActivityType(rawValue: activity.activityType) else { return }
@@ -617,9 +604,9 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
}
if isReadArticlesFiltered {
readFilterEnabledTable[feedID] = false
feedsHidingReadArticles.remove(feedID)
} else {
readFilterEnabledTable[feedID] = true
feedsHidingReadArticles.insert(feedID)
}
saveReadFilterEnabledTableToUserDefaults()
@@ -664,6 +651,11 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
}
func articleFor(_ articleID: String) -> Article? {
// Check if it's the currently displayed article
if let currentArticle, currentArticle.articleID == articleID {
return currentArticle
}
// Otherwise look in the timeline
return idToArticleDictionary[articleID]
}
@@ -696,7 +688,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
}
func isExpanded(_ containerID: ContainerIdentifier) -> Bool {
return expandedTable.contains(containerID)
return expandedContainers.contains(containerID)
}
func isExpanded(_ containerIdentifiable: ContainerIdentifiable) -> Bool {
@@ -716,14 +708,14 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
func expand(_ containerID: ContainerIdentifier) {
markExpanded(containerID)
rebuildBackingStores()
saveExpandedTableToUserDefaults()
saveExpandedContainersToUserDefaults()
}
/// This is a special function that expects the caller to change the disclosure arrow state outside this function.
/// Failure to do so will get the Sidebar into an invalid state.
func expand(_ node: Node) {
guard let containerID = (node.representedObject as? ContainerIdentifiable)?.containerID else { return }
lastExpandedTable.insert(containerID)
lastExpandedContainers.insert(containerID)
expand(containerID)
}
@@ -737,21 +729,21 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
}
}
rebuildBackingStores()
saveExpandedTableToUserDefaults()
saveExpandedContainersToUserDefaults()
}
func collapse(_ containerID: ContainerIdentifier) {
unmarkExpanded(containerID)
rebuildBackingStores()
clearTimelineIfNoLongerAvailable()
saveExpandedTableToUserDefaults()
saveExpandedContainersToUserDefaults()
}
/// This is a special function that expects the caller to change the disclosure arrow state outside this function.
/// Failure to do so will get the Sidebar into an invalid state.
func collapse(_ node: Node) {
guard let containerID = (node.representedObject as? ContainerIdentifiable)?.containerID else { return }
lastExpandedTable.remove(containerID)
lastExpandedContainers.remove(containerID)
collapse(containerID)
}
@@ -765,7 +757,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
}
rebuildBackingStores()
clearTimelineIfNoLongerAvailable()
saveExpandedTableToUserDefaults()
saveExpandedContainersToUserDefaults()
}
func mainFeedIndexPathForCurrentTimeline() -> IndexPath? {
@@ -791,7 +783,7 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
completion?()
return
}
currentFeedIndexPath = indexPath
mainFeedViewController.updateFeedSelection(animations: animations)
@@ -800,29 +792,31 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
}
if let ip = indexPath, let node = nodeFor(ip), let feed = node.representedObject as? Feed {
self.activityManager.selecting(feed: feed)
self.rootSplitViewController.show(.supplementary)
setTimelineFeed(feed, animated: false) {
if self.isReadFeedsFiltered {
self.rebuildBackingStores()
}
AppDefaults.shared.selectedSidebarItem = feed.feedID
completion?()
}
} else {
setTimelineFeed(nil, animated: false) {
if self.isReadFeedsFiltered {
self.rebuildBackingStores()
}
self.activityManager.invalidateSelecting()
self.rootSplitViewController.show(.primary)
AppDefaults.shared.selectedSidebarItem = nil
completion?()
}
}
}
func selectPrevFeed() {
@@ -860,18 +854,19 @@ final class SceneCoordinator: NSObject, UndoableCommandRunner {
func selectArticle(_ article: Article?, animations: Animations = [], isShowingExtractedArticle: Bool? = nil, articleWindowScrollY: Int? = nil) {
guard article != currentArticle else { return }
currentArticle = article
activityManager.reading(feed: timelineFeed, article: article)
if article == nil {
articleViewController?.article = nil
rootSplitViewController.show(.supplementary)
mainTimelineViewController?.updateArticleSelection(animations: animations)
return
}
rootSplitViewController.show(.secondary)
// Mark article as read before navigating to it, so the read status does not flash unread/read on display
markArticles(Set([article!]), statusKey: .read, flag: true)
@@ -1549,7 +1544,7 @@ private extension SceneCoordinator {
// Compute the differences in the shadow table rows and the expanded table entries
var changes = [ShadowTableChanges.RowChanges]()
let expandedTableDifference = lastExpandedTable.symmetricDifference(expandedTable)
let expandedTableDifference = lastExpandedContainers.symmetricDifference(expandedContainers)
for (section, newSectionRows) in newShadowTable.enumerated() {
var moves = Set<ShadowTableChanges.Move>()
@@ -1590,7 +1585,7 @@ private extension SceneCoordinator {
changes.append(ShadowTableChanges.RowChanges(section: section, deletes: deletes, inserts: inserts, reloads: reloads, moves: moves))
}
lastExpandedTable = expandedTable
lastExpandedContainers = expandedContainers
// Compute the difference in the shadow table sections
var moves = Set<ShadowTableChanges.Move>()
@@ -1695,7 +1690,7 @@ private extension SceneCoordinator {
}
func markExpanded(_ containerID: ContainerIdentifier) {
expandedTable.insert(containerID)
expandedContainers.insert(containerID)
}
func markExpanded(_ containerIdentifiable: ContainerIdentifiable) {
@@ -1711,7 +1706,7 @@ private extension SceneCoordinator {
}
func unmarkExpanded(_ containerID: ContainerIdentifier) {
expandedTable.remove(containerID)
expandedContainers.remove(containerID)
}
func unmarkExpanded(_ containerIdentifiable: ContainerIdentifiable) {
@@ -1726,41 +1721,12 @@ private extension SceneCoordinator {
}
}
private func saveExpandedTableToUserDefaults() {
let state = expandedTable.compactMap { containerID -> [String: String]? in
var stringDict = [String: String]()
for (key, value) in containerID.userInfo {
if let keyString = key as? String, let valueString = value as? String {
stringDict[keyString] = valueString
}
}
return stringDict.isEmpty ? nil : stringDict
}
AppDefaults.shared.containerExpandedWindowState = state
private func saveExpandedContainersToUserDefaults() {
AppDefaults.shared.expandedContainers = expandedContainers
}
private func saveReadFilterEnabledTableToUserDefaults() {
let enabledFeeds = readFilterEnabledTable.filter { $0.value == true }
let state = enabledFeeds.keys.compactMap { feedIdentifier -> [String: String]? in
var stringDict = [String: String]()
for (key, value) in feedIdentifier.userInfo {
if let keyString = key as? String, let valueString = value as? String {
stringDict[keyString] = valueString
}
}
return stringDict.isEmpty ? nil : stringDict
}
AppDefaults.shared.readArticlesFilterState = state
}
private func restoreReadFilterEnabledTableFromUserDefaults() {
guard let state = AppDefaults.shared.readArticlesFilterState else { return }
for dict in state {
if let feedIdentifier = FeedIdentifier(userInfo: dict) {
readFilterEnabledTable[feedIdentifier] = true
}
}
AppDefaults.shared.sidebarItemsHidingReadArticles = feedsHidingReadArticles
}
// MARK: Select Prev Unread
@@ -1999,6 +1965,12 @@ private extension SceneCoordinator {
func replaceArticles(with sortedArticles: ArticleArray, animated: Bool) {
if articles != sortedArticles {
articles = sortedArticles
// Clear current article if it's no longer in the timeline
if let currentArticle, !sortedArticles.contains(where: { $0.articleID == currentArticle.articleID && $0.accountID == currentArticle.accountID }) {
selectArticle(nil)
}
updateShowNamesAndIcons()
updateUnreadCount()
mainTimelineViewController?.reloadArticles(animated: animated)
@@ -2131,7 +2103,7 @@ private extension SceneCoordinator {
func handleSelectFeed(_ userInfo: [AnyHashable : Any]?) {
guard let userInfo = userInfo,
let feedIdentifierUserInfo = userInfo[UserInfoKey.feedIdentifier] as? [AnyHashable : AnyHashable],
let feedIdentifierUserInfo = userInfo[UserInfoKey.feedIdentifier] as? [String: String],
let feedIdentifier = FeedIdentifier(userInfo: feedIdentifierUserInfo) else {
return
}
@@ -2216,7 +2188,7 @@ private extension SceneCoordinator {
}
func restoreFeedSelection(_ userInfo: [AnyHashable : Any], accountID: String, webFeedID: String, articleID: String) -> Bool {
guard let feedIdentifierUserInfo = userInfo[UserInfoKey.feedIdentifier] as? [AnyHashable : AnyHashable],
guard let feedIdentifierUserInfo = userInfo[UserInfoKey.feedIdentifier] as? [String: String],
let feedIdentifier = FeedIdentifier(userInfo: feedIdentifierUserInfo) else {
return false
}
+7 -5
View File
@@ -28,8 +28,8 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
rootViewController.preferredDisplayMode = .oneBesideSecondary
Task { @MainActor in
// Ensure Feeds view shows on first run on iPad — otherwise the UI is empty.
if UIDevice.current.userInterfaceIdiom == .pad && AppDefaults.shared.isFirstRun {
// Ensure Feeds view shows on iPad — otherwise the UI may be empty.
if UIDevice.current.userInterfaceIdiom == .pad {
rootViewController.show(.primary)
}
}
@@ -38,7 +38,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
rootViewController.coordinator = coordinator
rootViewController.delegate = coordinator
coordinator.restoreWindowState(session.stateRestorationActivity)
coordinator.restoreWindowState(activity: session.stateRestorationActivity)
updateUserInterfaceStyle()
@@ -58,8 +58,10 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
coordinator.handle(notificationResponse)
return
}
if let userActivity = connectionOptions.userActivities.first ?? session.stateRestorationActivity {
// Handle activities from external sources (Handoff, Spotlight, Siri Shortcuts).
// Skip handling session.stateRestorationActivity since UserDefaults now handles state restoration.
if let userActivity = connectionOptions.userActivities.first {
coordinator.handle(userActivity)
}
+18 -2
View File
@@ -414,8 +414,24 @@ private extension SettingsViewController {
}
func importOPMLDocumentPicker() {
let docPicker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.opml, UTType.xml], asCopy: true)
var contentTypes: [UTType] = []
// Create UTType for .opml files by extension, without requiring conformance.
// This ensures files ending in .opml can be selected no matter how OPML is registered.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4858>
if let opmlByExtension = UTType(filenameExtension: "opml") {
contentTypes.append(opmlByExtension)
}
// Also try the registered org.opml.opml UTI if it exists
if let registeredOPML = UTType("org.opml.opml") {
contentTypes.append(registeredOPML)
}
// Include XML as a fallback
contentTypes.append(.xml)
let docPicker = UIDocumentPickerViewController(forOpeningContentTypes: contentTypes, asCopy: true)
docPicker.delegate = self
docPicker.modalPresentationStyle = .formSheet
self.present(docPicker, animated: true)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff