mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-11-28 16:26:04 +00:00
1899 lines
63 KiB
Swift
1899 lines
63 KiB
Swift
//
|
||
// TimelineViewController.swift
|
||
// NetNewsWire
|
||
//
|
||
// Created by Brent Simmons on 7/26/15.
|
||
// Copyright © 2015 Ranchero Software, LLC. All rights reserved.
|
||
//
|
||
|
||
import Foundation
|
||
import RSCore
|
||
import Articles
|
||
import Account
|
||
import os
|
||
import Images
|
||
import RSWeb
|
||
|
||
@MainActor protocol TimelineDelegate: AnyObject {
|
||
func timelineSelectionDidChange(_: TimelineViewController, selectedArticles: [Article]?)
|
||
func timelineRequestedFeedSelection(_: TimelineViewController, feed: Feed)
|
||
func timelineInvalidatedRestorationState(_: TimelineViewController)
|
||
func timelineRequestedSortChange(_: TimelineViewController, parameters: ArticleSortParameters)
|
||
}
|
||
|
||
enum TimelineShowFeedName: Sendable {
|
||
case none
|
||
case byline
|
||
case feed
|
||
}
|
||
|
||
final class TimelineViewController: NSViewController, UndoableCommandRunner, UnreadCountProvider {
|
||
|
||
@IBOutlet var tableView: TimelineTableView!
|
||
|
||
var sharingServicePickerDelegate: NSSharingServicePickerDelegate?
|
||
|
||
private var readFilterEnabledTable = [SidebarItemIdentifier: Bool]()
|
||
|
||
var isReadFiltered: Bool? {
|
||
guard representedObjects?.count == 1, let timelineFeed = representedObjects?.first as? SidebarItem else {
|
||
return nil
|
||
}
|
||
guard timelineFeed.defaultReadFilterType != .alwaysRead else {
|
||
return nil
|
||
}
|
||
if let sidebarItemID = timelineFeed.sidebarItemID, let readFiltered = readFilterEnabledTable[sidebarItemID] {
|
||
return readFiltered
|
||
}
|
||
return timelineFeed.defaultReadFilterType == .read
|
||
}
|
||
|
||
var isCleanUpAvailable: Bool {
|
||
let isEligibleForCleanUp: Bool?
|
||
|
||
if representedObjects?.count == 1, let timelineFeed = representedObjects?.first as? SidebarItem, timelineFeed.defaultReadFilterType == .alwaysRead {
|
||
isEligibleForCleanUp = true
|
||
} else {
|
||
isEligibleForCleanUp = isReadFiltered
|
||
}
|
||
|
||
guard isEligibleForCleanUp ?? false else { return false }
|
||
|
||
let readSelectedCount = selectedArticles.filter({ $0.status.read }).count
|
||
let readArticleCount = articles.count - unreadCount
|
||
let availableToCleanCount = readArticleCount - readSelectedCount
|
||
|
||
return availableToCleanCount > 0
|
||
}
|
||
|
||
var representedObjects: [AnyObject]? {
|
||
didSet {
|
||
if !representedObjectArraysAreEqual(oldValue, representedObjects) {
|
||
seedReadFilterForFolders()
|
||
unreadCount = 0
|
||
|
||
selectionDidChange(nil)
|
||
if showsSearchResults {
|
||
fetchAndReplaceArticlesAsync()
|
||
} else {
|
||
fetchAndReplaceArticlesSync()
|
||
if articles.count > 0 {
|
||
tableView.scrollRowToVisible(0)
|
||
}
|
||
updateUnreadCount()
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
var windowState: TimelineWindowState {
|
||
let readArticlesFilterStateKeys = readFilterEnabledTable.keys.compactMap { $0.userInfo }
|
||
let readArticlesFilterStateValues = readFilterEnabledTable.values.compactMap( { $0 })
|
||
|
||
if selectedArticles.count == 1 {
|
||
let path = selectedArticles.first!.pathUserInfo
|
||
return TimelineWindowState(readArticlesFilterStateKeys: readArticlesFilterStateKeys,
|
||
readArticlesFilterStateValues: readArticlesFilterStateValues,
|
||
selectedAccountID: path[ArticlePathKey.accountID] as? String,
|
||
selectedArticleID: path[ArticlePathKey.articleID] as? String,
|
||
sortParameters: sortParameters)
|
||
} else {
|
||
return TimelineWindowState(readArticlesFilterStateKeys: readArticlesFilterStateKeys,
|
||
readArticlesFilterStateValues: readArticlesFilterStateValues,
|
||
selectedAccountID: nil,
|
||
selectedArticleID: nil,
|
||
sortParameters: sortParameters)
|
||
}
|
||
|
||
}
|
||
weak var delegate: TimelineDelegate?
|
||
var sharingServiceDelegate: NSSharingServiceDelegate?
|
||
|
||
var showsSearchResults = false
|
||
var selectedArticles: [Article] {
|
||
return articles.articlesForIndexes(tableView.selectedRowIndexes)
|
||
}
|
||
|
||
var hasAtLeastOneSelectedArticle: Bool {
|
||
return tableView.selectedRow != -1
|
||
}
|
||
|
||
var articles = ArticleArray() {
|
||
didSet {
|
||
defer {
|
||
updateUnreadCount()
|
||
}
|
||
|
||
if articles == oldValue {
|
||
return
|
||
}
|
||
|
||
if articles.representSameArticlesInSameOrder(as: oldValue) {
|
||
// When the array is the same — same articles, same order —
|
||
// but some data in some of the articles may have changed.
|
||
// Just reload visible cells in this case: don’t call reloadData.
|
||
articleRowMap = [String: [Int]]()
|
||
remeasureRowHeights(rowsWithChangedArticles(comparedWith: oldValue))
|
||
reloadVisibleCells()
|
||
return
|
||
}
|
||
|
||
if let representedObjects, representedObjects.count == 1 && representedObjects.first is Feed {
|
||
showFeedNames = .byline
|
||
} else {
|
||
showFeedNames = .feed
|
||
}
|
||
updateShowIcons() // Automatic depends on these articles’ author avatars, even when showFeedNames didn’t change
|
||
|
||
articleRowMap = [String: [Int]]()
|
||
removeRowHeightsForMissingArticles()
|
||
tableView.reloadData()
|
||
if showIcons {
|
||
IconImageCache.shared.prefetchImagesForArticles(articles)
|
||
}
|
||
}
|
||
}
|
||
|
||
var unreadCount: Int = 0 {
|
||
didSet {
|
||
if unreadCount != oldValue {
|
||
postUnreadCountDidChangeNotification()
|
||
}
|
||
}
|
||
}
|
||
|
||
var undoableCommands = [UndoableCommand]()
|
||
|
||
private var fetchSerialNumber = 0
|
||
private let fetchRequestQueue = FetchRequestQueue()
|
||
private var exceptionArticleFetcher: ArticleFetcher?
|
||
private var articleRowMap = [String: [Int]]() // articleID: rowIndex
|
||
private var cellAppearance: TimelineCellAppearance!
|
||
private var cellAppearanceWithIcon: TimelineCellAppearance!
|
||
private var showFeedNames: TimelineShowFeedName = .none {
|
||
didSet {
|
||
if showFeedNames != oldValue {
|
||
rowHeights.removeAll()
|
||
updateShowIcons()
|
||
updateTableViewRowHeight()
|
||
reloadVisibleCells()
|
||
}
|
||
}
|
||
}
|
||
|
||
private(set) var showIcons = false {
|
||
didSet {
|
||
if showIcons != oldValue {
|
||
rowHeights.removeAll()
|
||
}
|
||
}
|
||
}
|
||
private var estimatedRowHeight: CGFloat = 0.0 // For rows not yet measured
|
||
private var rowHeights = [ArticleIdentityKey: TimelineRowHeight]() // Height measured at rowHeightWidth
|
||
private var rowHeightWidth: CGFloat = 0.0 // The width of a standard-layout cell
|
||
private var rowHeightMeasuringStartRow: Int? // Where the next measuring pass starts
|
||
private var isRowHeightMeasuringScheduled = false
|
||
private static let rowHeightBatchSize = 500
|
||
private var thumbnailsDisplay = AppDefaults.timelineThumbnailsDisplay {
|
||
didSet {
|
||
if thumbnailsDisplay != oldValue {
|
||
thumbnailsDisplayDidChange()
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Narrow enough that the prototype’s title uses every line.
|
||
private static let prototypeRowWidth: CGFloat = 100.0
|
||
|
||
/// Nil when the timeline doesn’t show thumbnails. Column layout never shows them.
|
||
private var thumbnailMode: ThumbnailMode? {
|
||
layout == .standard ? thumbnailsDisplay.thumbnailMode : nil
|
||
}
|
||
|
||
private var didRegisterForNotifications = false
|
||
static let fetchAndMergeArticlesQueue = CoalescingQueue(name: "Fetch and Merge Articles", interval: 0.5, maxInterval: 2.0)
|
||
|
||
// Owned by the window’s TimelineContainerViewController.
|
||
// Before the view loads there is nothing to re-sort — the first fetch uses the current value.
|
||
var sortParameters = ArticleSortParameters.newestFirst {
|
||
didSet {
|
||
if isViewLoaded && sortParameters != oldValue {
|
||
sortParametersDidChange()
|
||
applySortDescriptorsToTableView()
|
||
}
|
||
}
|
||
}
|
||
// Also owned by the container, which pushes the current value before and after the view loads.
|
||
var layout = TimelineLayout.standard {
|
||
didSet {
|
||
if isViewLoaded && layout != oldValue {
|
||
layoutDidChange()
|
||
}
|
||
}
|
||
}
|
||
// The nib’s single column, kept so standard layout can put it back.
|
||
var standardColumn: NSTableColumn?
|
||
// Set while columns are added and autosaved state is restored, which fires sortDescriptorsDidChange.
|
||
var isConfiguringTableColumns = false
|
||
private var textSize = AppDefaults.timelineTextSize {
|
||
didSet {
|
||
if textSize != oldValue {
|
||
cellAppearanceSettingDidChange()
|
||
}
|
||
}
|
||
}
|
||
private var numberOfLines = AppDefaults.timelineNumberOfLines {
|
||
didSet {
|
||
if numberOfLines != oldValue {
|
||
cellAppearanceSettingDidChange()
|
||
}
|
||
}
|
||
}
|
||
private var showFullTitles = AppDefaults.timelineShowFullTitles {
|
||
didSet {
|
||
if showFullTitles != oldValue {
|
||
cellAppearanceSettingDidChange()
|
||
}
|
||
}
|
||
}
|
||
private var feedNameAndDateAboveTitle = AppDefaults.timelineFeedNameAndDateAboveTitle {
|
||
didSet {
|
||
if feedNameAndDateAboveTitle != oldValue {
|
||
cellAppearanceSettingDidChange()
|
||
}
|
||
}
|
||
}
|
||
private var fadesReadArticles = AppDefaults.timelineFadeReadArticles {
|
||
didSet {
|
||
if fadesReadArticles != oldValue {
|
||
reloadVisibleCells()
|
||
}
|
||
}
|
||
}
|
||
private static let readArticleAlphaValue: CGFloat = 0.6
|
||
|
||
/// Two accounts can have articles with the same articleID — the same feed in On My Mac and iCloud, for instance.
|
||
private struct ArticleIdentityKey: Hashable {
|
||
let accountID: String
|
||
let articleID: String
|
||
|
||
init(_ article: Article) {
|
||
self.accountID = article.accountID
|
||
self.articleID = article.articleID
|
||
}
|
||
}
|
||
|
||
/// A changed article is a new instance, so `article` tells whether the height is still current.
|
||
private struct TimelineRowHeight {
|
||
let article: Article
|
||
let showsThumbnail: Bool
|
||
let height: CGFloat
|
||
}
|
||
|
||
private var previouslySelectedArticleKeys: [ArticleIdentityKey]?
|
||
|
||
private var oneSelectedArticle: Article? {
|
||
return selectedArticles.count == 1 ? selectedArticles.first : nil
|
||
}
|
||
|
||
private let keyboardDelegate = TimelineKeyboardDelegate()
|
||
|
||
private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "TimelineViewController")
|
||
|
||
convenience init(delegate: TimelineDelegate) {
|
||
self.init(nibName: "TimelineTableView", bundle: nil)
|
||
self.delegate = delegate
|
||
}
|
||
|
||
override func viewDidLoad() {
|
||
// The search timeline can be created long before its view loads, and defaults are observed only from here on.
|
||
textSize = AppDefaults.timelineTextSize
|
||
numberOfLines = AppDefaults.timelineNumberOfLines
|
||
showFullTitles = AppDefaults.timelineShowFullTitles
|
||
feedNameAndDateAboveTitle = AppDefaults.timelineFeedNameAndDateAboveTitle
|
||
fadesReadArticles = AppDefaults.timelineFadeReadArticles
|
||
updateGridStyle()
|
||
thumbnailsDisplay = AppDefaults.timelineThumbnailsDisplay
|
||
updateCellAppearances()
|
||
|
||
updateEstimatedRowHeight()
|
||
tableView.target = self
|
||
tableView.doubleAction = #selector(openArticleInBrowser(_:))
|
||
tableView.setDraggingSourceOperationMask(.copy, forLocal: false)
|
||
tableView.keyboardDelegate = keyboardDelegate
|
||
tableView.rowHeightDelegate = self
|
||
tableView.style = .inset
|
||
tableView.gridColor = .separatorColor
|
||
|
||
standardColumn = tableView.tableColumns.first
|
||
configureTableView(for: layout)
|
||
updateGridStyle()
|
||
updateShowIcons()
|
||
|
||
if !didRegisterForNotifications {
|
||
NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleFeedIconImageDidChange(_:)), name: .feedIconImageDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleAuthorAvatarImageDidChange(_:)), name: .authorAvatarImageDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleGrayscaleIconsDidChange(_:)), name: .grayscaleIconsDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleThumbnailDidBecomeAvailable(_:)), name: .thumbnailDidBecomeAvailable, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThumbnailDownloadDidFail(_:)), name: .articleThumbnailDownloadDidFail, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleNetworkStatusDidChange(_:)), name: .networkStatusDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(accountDidDownloadArticles(_:)), name: .AccountDidDownloadArticles, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(accountStateDidChange(_:)), name: .AccountStateDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidAddAccount, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(userDidDeleteAccount(_:)), name: .UserDidDeleteAccount, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleSidebarDidAcceptDrop(_:)), name: .SidebarDidAcceptDrop, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(containerChildrenDidChange(_:)), name: .ChildrenDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineShowSeparatorsDidChange(_:)), name: .timelineShowSeparatorsDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineThumbnailsDisplayDidChange(_:)), name: .timelineThumbnailsDisplayDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFeedIconsDisplayDidChange(_:)), name: .timelineFeedIconsDisplayDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineIconSizeDidChange(_:)), name: .timelineIconSizeDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineTextSizeDidChange(_:)), name: .timelineTextSizeDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineNumberOfLinesDidChange(_:)), name: .timelineNumberOfLinesDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineShowFullTitlesDidChange(_:)), name: .timelineShowFullTitlesDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFeedNameAndDateAboveTitleDidChange(_:)), name: .timelineFeedNameAndDateAboveTitleDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFadeReadArticlesDidChange(_:)), name: .timelineFadeReadArticlesDidChange, object: nil)
|
||
didRegisterForNotifications = true
|
||
}
|
||
|
||
sharingServicePickerDelegate = SharingServicePickerDelegate(self.view.window)
|
||
}
|
||
|
||
override func viewDidAppear() {
|
||
sharingServiceDelegate = SharingServiceDelegate(self.view.window)
|
||
}
|
||
|
||
override func viewDidLayout() {
|
||
super.viewDidLayout()
|
||
fitTableViewToVisibleWidthInStandardLayout()
|
||
}
|
||
|
||
// MARK: - API
|
||
|
||
func markAllAsRead(completion: (() -> Void)? = nil) {
|
||
guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: articles, markingRead: true, undoManager: undoManager, completion: completion) else {
|
||
completion?()
|
||
return
|
||
}
|
||
runCommand(markReadCommand)
|
||
}
|
||
|
||
func canMarkAllAsRead() -> Bool {
|
||
return articles.canMarkAllAsRead()
|
||
}
|
||
|
||
func canMarkSelectedArticlesAsRead() -> Bool {
|
||
return selectedArticles.canMarkAllAsRead()
|
||
}
|
||
|
||
func representsThisObjectOnly(_ object: AnyObject) -> Bool {
|
||
guard let representedObjects = representedObjects else {
|
||
return false
|
||
}
|
||
if representedObjects.count != 1 {
|
||
return false
|
||
}
|
||
return representedObjects.first! === object
|
||
}
|
||
|
||
func cleanUp() {
|
||
fetchAndReplacePreservingSelection()
|
||
}
|
||
|
||
func toggleReadFilter() {
|
||
guard let filter = isReadFiltered,
|
||
let sidebarItemID = (representedObjects?.first as? SidebarItem)?.sidebarItemID else {
|
||
return
|
||
}
|
||
if filter {
|
||
noteSidebarItemShowsReadArticles(sidebarItemID)
|
||
} else {
|
||
noteSidebarItemHidesReadArticles(sidebarItemID)
|
||
}
|
||
delegate?.timelineInvalidatedRestorationState(self)
|
||
fetchAndReplacePreservingSelection()
|
||
}
|
||
|
||
// MARK: State Restoration
|
||
|
||
private func noteSidebarItemHidesReadArticles(_ sidebarItemID: SidebarItemIdentifier) {
|
||
readFilterEnabledTable[sidebarItemID] = true
|
||
}
|
||
|
||
private func noteSidebarItemShowsReadArticles(_ sidebarItemID: SidebarItemIdentifier) {
|
||
readFilterEnabledTable[sidebarItemID] = false
|
||
}
|
||
|
||
func restoreState(from state: TimelineWindowState) {
|
||
for i in 0..<state.readArticlesFilterStateKeys.count {
|
||
if let sidebarItemID = SidebarItemIdentifier(userInfo: state.readArticlesFilterStateKeys[i]) {
|
||
let hidesReadArticles = state.readArticlesFilterStateValues[i]
|
||
if hidesReadArticles {
|
||
noteSidebarItemHidesReadArticles(sidebarItemID)
|
||
} else {
|
||
noteSidebarItemShowsReadArticles(sidebarItemID)
|
||
}
|
||
}
|
||
}
|
||
|
||
if let selectedAccountID = state.selectedAccountID,
|
||
let account = AccountManager.shared.existingAccount(accountID: selectedAccountID),
|
||
let selectedArticleID = state.selectedArticleID {
|
||
|
||
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: selectedArticleID)
|
||
fetchAndReplaceArticlesSync()
|
||
|
||
if let selectedIndex = articles.firstIndex(where: { $0.articleID == selectedArticleID }) {
|
||
tableView.selectRow(selectedIndex)
|
||
DispatchQueue.main.async {
|
||
self.tableView.scrollTo(row: selectedIndex)
|
||
}
|
||
focus()
|
||
}
|
||
} else {
|
||
fetchAndReplaceArticlesSync()
|
||
}
|
||
}
|
||
|
||
/// Restore state using legacy state restoration data.
|
||
///
|
||
/// TODO: Delete for NetNewsWire 7.
|
||
func restoreLegacyState(from state: [AnyHashable: Any]) {
|
||
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 sidebarItemID = SidebarItemIdentifier(userInfo: readArticlesFilterStateKeys[i]) {
|
||
let hidesReadArticles = readArticlesFilterStateValues[i]
|
||
if hidesReadArticles {
|
||
noteSidebarItemHidesReadArticles(sidebarItemID)
|
||
} else {
|
||
noteSidebarItemShowsReadArticles(sidebarItemID)
|
||
}
|
||
}
|
||
}
|
||
|
||
if let articlePathUserInfo = state[UserInfoKey.articlePath] as? [AnyHashable: Any],
|
||
let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String,
|
||
let account = AccountManager.shared.existingAccount(accountID: accountID),
|
||
let articleID = articlePathUserInfo[ArticlePathKey.articleID] as? String {
|
||
|
||
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: articleID)
|
||
fetchAndReplaceArticlesSync()
|
||
|
||
if let selectedIndex = articles.firstIndex(where: { $0.articleID == articleID }) {
|
||
tableView.selectRow(selectedIndex)
|
||
DispatchQueue.main.async {
|
||
self.tableView.scrollTo(row: selectedIndex)
|
||
}
|
||
focus()
|
||
}
|
||
} else {
|
||
fetchAndReplaceArticlesSync()
|
||
}
|
||
}
|
||
|
||
// MARK: - Actions
|
||
|
||
@objc func openArticleInBrowser(_ sender: Any?) {
|
||
let article: Article?
|
||
|
||
if let tableView = sender as? NSTableView, tableView === self.tableView, let clickedArticle = articles.articleAtRow(tableView.clickedRow) {
|
||
article = clickedArticle
|
||
if !clickedArticle.status.read {
|
||
markArticles(Set([clickedArticle]), statusKey: .read, flag: true)
|
||
}
|
||
} else {
|
||
article = oneSelectedArticle
|
||
}
|
||
|
||
if let link = article?.preferredLink {
|
||
Browser.open(link, invertPreference: NSApp.currentEvent?.modifierFlags.contains(.shift) ?? false)
|
||
}
|
||
}
|
||
|
||
@IBAction func toggleStatusOfSelectedArticles(_ sender: Any?) {
|
||
guard !selectedArticles.isEmpty else {
|
||
return
|
||
}
|
||
let articles = selectedArticles
|
||
let status = articles.first!.status
|
||
let markAsRead = !status.read
|
||
|
||
if markAsRead {
|
||
markSelectedArticlesAsRead(sender)
|
||
} else {
|
||
markSelectedArticlesAsUnread(sender)
|
||
}
|
||
}
|
||
|
||
@IBAction func markSelectedArticlesAsRead(_ sender: Any?) {
|
||
guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: selectedArticles, markingRead: true, undoManager: undoManager) else {
|
||
return
|
||
}
|
||
runCommand(markReadCommand)
|
||
}
|
||
|
||
@IBAction func markSelectedArticlesAsUnread(_ sender: Any?) {
|
||
guard let undoManager = undoManager, let markUnreadCommand = MarkStatusCommand(initialArticles: selectedArticles, markingRead: false, undoManager: undoManager) else {
|
||
return
|
||
}
|
||
runCommand(markUnreadCommand)
|
||
}
|
||
|
||
@IBAction func copy(_ sender: Any?) {
|
||
NSPasteboard.general.copyObjects(selectedArticles)
|
||
}
|
||
|
||
@IBAction func selectNextUp(_ sender: Any?) {
|
||
guard let lastSelectedRow = tableView.selectedRowIndexes.last else {
|
||
return
|
||
}
|
||
|
||
let nextRowIndex = lastSelectedRow - 1
|
||
if nextRowIndex <= 0 {
|
||
tableView.scrollTo(row: 0, extraHeight: 0)
|
||
}
|
||
|
||
tableView.selectRow(nextRowIndex)
|
||
|
||
if scrollToRowIfNotFullyVisible(nextRowIndex) {
|
||
return
|
||
}
|
||
|
||
scrollToRowIfNotFullyVisible(nextRowIndex - 1)
|
||
}
|
||
|
||
@IBAction func selectNextDown(_ sender: Any?) {
|
||
guard let firstSelectedRow = tableView.selectedRowIndexes.first else {
|
||
return
|
||
}
|
||
|
||
let tableMaxIndex = tableView.numberOfRows - 1
|
||
let nextRowIndex = firstSelectedRow + 1
|
||
if nextRowIndex >= tableMaxIndex {
|
||
tableView.scrollTo(row: tableMaxIndex, extraHeight: 0)
|
||
}
|
||
|
||
tableView.selectRow(nextRowIndex)
|
||
|
||
if scrollToRowIfNotFullyVisible(nextRowIndex) {
|
||
return
|
||
}
|
||
|
||
scrollToRowIfNotFullyVisible(nextRowIndex + 1)
|
||
}
|
||
|
||
func toggleReadStatusForSelectedArticles() {
|
||
// If any one of the selected articles is unread, then mark them as read.
|
||
// If all articles are read, then mark them as unread them.
|
||
|
||
let commandStatus = markReadCommandStatus()
|
||
let markingRead: Bool
|
||
switch commandStatus {
|
||
case .canMark:
|
||
markingRead = true
|
||
case .canUnmark:
|
||
markingRead = false
|
||
case .canDoNothing:
|
||
return
|
||
}
|
||
|
||
guard let undoManager = undoManager, let markStarredCommand = MarkStatusCommand(initialArticles: selectedArticles, markingRead: markingRead, undoManager: undoManager) else {
|
||
return
|
||
}
|
||
|
||
runCommand(markStarredCommand)
|
||
}
|
||
|
||
func toggleStarredStatusForSelectedArticles() {
|
||
|
||
// If any one of the selected articles is not starred, then star them.
|
||
// If all articles are starred, then unstar them.
|
||
|
||
let commandStatus = markStarredCommandStatus()
|
||
let starring: Bool
|
||
switch commandStatus {
|
||
case .canMark:
|
||
starring = true
|
||
case .canUnmark:
|
||
starring = false
|
||
case .canDoNothing:
|
||
return
|
||
}
|
||
|
||
guard let undoManager = undoManager, let markStarredCommand = MarkStatusCommand(initialArticles: selectedArticles, markingStarred: starring, undoManager: undoManager) else {
|
||
return
|
||
}
|
||
runCommand(markStarredCommand)
|
||
}
|
||
|
||
func markStarredCommandStatus() -> MarkCommandValidationStatus {
|
||
return MarkCommandValidationStatus.statusFor(selectedArticles) { $0.anyArticleIsUnstarred() }
|
||
}
|
||
|
||
func markReadCommandStatus() -> MarkCommandValidationStatus {
|
||
let articles = selectedArticles
|
||
|
||
if articles.anyArticleIsUnread() {
|
||
return .canMark
|
||
}
|
||
|
||
if articles.anyArticleIsReadAndCanMarkUnread() {
|
||
return .canUnmark
|
||
}
|
||
|
||
return .canDoNothing
|
||
}
|
||
|
||
func markOlderArticlesRead() {
|
||
markOlderArticlesRead(selectedArticles)
|
||
}
|
||
|
||
func markAboveArticlesRead() {
|
||
markAboveArticlesRead(selectedArticles)
|
||
}
|
||
|
||
func markBelowArticlesRead() {
|
||
markBelowArticlesRead(selectedArticles)
|
||
}
|
||
|
||
func canMarkAboveArticlesAsRead() -> Bool {
|
||
guard let first = selectedArticles.first else { return false }
|
||
return articles.articlesAbove(article: first).canMarkAllAsRead()
|
||
}
|
||
|
||
func canMarkBelowArticlesAsRead() -> Bool {
|
||
guard let last = selectedArticles.last else { return false }
|
||
return articles.articlesBelow(article: last).canMarkAllAsRead()
|
||
}
|
||
|
||
func markOlderArticlesRead(_ selectedArticles: [Article]) {
|
||
// Mark articles older than the selectedArticles(s) as read.
|
||
|
||
var cutoffDate: Date?
|
||
for article in selectedArticles {
|
||
if cutoffDate == nil {
|
||
cutoffDate = article.logicalDatePublished
|
||
} else if cutoffDate! > article.logicalDatePublished {
|
||
cutoffDate = article.logicalDatePublished
|
||
}
|
||
}
|
||
if cutoffDate == nil {
|
||
return
|
||
}
|
||
|
||
let articlesToMark = articles.filter { $0.logicalDatePublished < cutoffDate! }
|
||
if articlesToMark.isEmpty {
|
||
return
|
||
}
|
||
|
||
guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: articlesToMark, markingRead: true, undoManager: undoManager) else {
|
||
return
|
||
}
|
||
runCommand(markReadCommand)
|
||
}
|
||
|
||
func markAboveArticlesRead(_ selectedArticles: [Article]) {
|
||
guard let first = selectedArticles.first else { return }
|
||
let articlesToMark = articles.articlesAbove(article: first)
|
||
guard !articlesToMark.isEmpty else { return }
|
||
guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: articlesToMark, markingRead: true, undoManager: undoManager) else {
|
||
return
|
||
}
|
||
runCommand(markReadCommand)
|
||
}
|
||
|
||
func markBelowArticlesRead(_ selectedArticles: [Article]) {
|
||
guard let last = selectedArticles.last else { return }
|
||
let articlesToMark = articles.articlesBelow(article: last)
|
||
guard !articlesToMark.isEmpty else { return }
|
||
guard let undoManager = undoManager, let markReadCommand = MarkStatusCommand(initialArticles: articlesToMark, markingRead: true, undoManager: undoManager) else {
|
||
return
|
||
}
|
||
runCommand(markReadCommand)
|
||
}
|
||
|
||
// MARK: - Navigation
|
||
|
||
func goToDeepLink(for userInfo: [AnyHashable: Any]) {
|
||
guard let articleID = userInfo[ArticlePathKey.articleID] as? String else { return }
|
||
|
||
if isReadFiltered ?? false {
|
||
if let accountName = userInfo[ArticlePathKey.accountName] as? String,
|
||
let account = AccountManager.shared.existingActiveAccount(forDisplayName: accountName) {
|
||
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: articleID)
|
||
fetchAndReplaceArticlesSync()
|
||
}
|
||
}
|
||
|
||
guard let ix = articles.firstIndex(where: { $0.articleID == articleID }) else { return }
|
||
|
||
NSCursor.setHiddenUntilMouseMoves(true)
|
||
tableView.selectRow(ix)
|
||
tableView.scrollTo(row: ix)
|
||
}
|
||
|
||
func goToNextUnread(wrappingToTop wrapping: Bool = false) {
|
||
guard let ix = indexOfNextUnreadArticle() else {
|
||
return
|
||
}
|
||
NSCursor.setHiddenUntilMouseMoves(true)
|
||
tableView.selectRow(ix)
|
||
tableView.scrollTo(row: ix)
|
||
}
|
||
|
||
func canGoToNextUnread(wrappingToTop wrapping: Bool = false) -> Bool {
|
||
return indexOfNextUnreadArticle(wrappingToTop: wrapping) != nil
|
||
}
|
||
|
||
func indexOfNextUnreadArticle(wrappingToTop wrapping: Bool = false) -> Int? {
|
||
return articles.rowOfNextUnreadArticle(tableView.selectedRow, wrappingToTop: wrapping)
|
||
}
|
||
|
||
func focus() {
|
||
guard let window = tableView.window else {
|
||
return
|
||
}
|
||
|
||
window.makeFirstResponderUnlessDescendantIsFirstResponder(tableView)
|
||
if !hasAtLeastOneSelectedArticle && articles.count > 0 {
|
||
tableView.selectRowAndScrollToVisible(0)
|
||
}
|
||
}
|
||
|
||
// MARK: - Notifications
|
||
|
||
@objc func statusesDidChange(_ note: Notification) {
|
||
guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set<String> else {
|
||
return
|
||
}
|
||
reloadVisibleCells(for: articleIDs)
|
||
updateUnreadCount()
|
||
}
|
||
|
||
@objc func handleFeedIconImageDidChange(_ notification: Notification) {
|
||
guard showIcons, let feed = notification.userInfo?[UserInfoKey.feed] as? Feed else {
|
||
return
|
||
}
|
||
let indexesToReload = tableView.indexesOfAvailableRowsPassingTest { (row) -> Bool in
|
||
guard let article = articles.articleAtRow(row) else {
|
||
return false
|
||
}
|
||
return feed == article.feed
|
||
}
|
||
if let indexesToReload = indexesToReload {
|
||
reloadCells(for: indexesToReload)
|
||
}
|
||
}
|
||
|
||
@objc func handleAuthorAvatarImageDidChange(_ notification: Notification) {
|
||
guard showIcons, let avatarURL = notification.userInfo?[UserInfoKey.url] as? String else {
|
||
return
|
||
}
|
||
|
||
let indexesToReload = tableView.indexesOfAvailableRowsPassingTest { (row) -> Bool in
|
||
guard let article = articles.articleAtRow(row), let authors = article.authors, !authors.isEmpty else {
|
||
return false
|
||
}
|
||
for author in authors {
|
||
if author.avatarURL == avatarURL {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
if let indexesToReload = indexesToReload {
|
||
reloadCells(for: indexesToReload)
|
||
}
|
||
}
|
||
|
||
@objc func handleGrayscaleIconsDidChange(_ notification: Notification) {
|
||
guard showIcons else {
|
||
return
|
||
}
|
||
reloadVisibleCells()
|
||
}
|
||
|
||
@objc func handleThumbnailDidBecomeAvailable(_ notification: Notification) {
|
||
guard let thumbnailMode, let url = notification.userInfo?[ThumbnailDownloader.urlKey] as? String else {
|
||
return
|
||
}
|
||
// The row already has room for the thumbnail, so only the image changes.
|
||
tableView.enumerateAvailableRowViews { rowView, row in
|
||
guard let article = articles.articleAtRow(row), ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) == url, let cell = cellForRowView(rowView) as? TimelineTableCellView, let thumbnail = ThumbnailDownloader.shared.thumbnail(url: url, mode: thumbnailMode, feedName: article.feed?.nameForDisplay, articleTitle: article.title) else {
|
||
return
|
||
}
|
||
cell.thumbnail = thumbnail
|
||
}
|
||
}
|
||
|
||
@objc func handleArticleThumbnailDownloadDidFail(_ notification: Notification) {
|
||
guard thumbnailMode != nil, let articleIDs = notification.userInfo?[ArticleThumbnailFinder.articleIDsKey] as? Set<String> else {
|
||
return
|
||
}
|
||
// Articles that used the failed URL now get their next source, or none.
|
||
thumbnailURLsDidChange(for: articleIDs)
|
||
}
|
||
|
||
@objc func handleNetworkStatusDidChange(_ notification: Notification) {
|
||
guard thumbnailMode != nil else {
|
||
return
|
||
}
|
||
// After ArticleThumbnailFinder forgets its choices, which it does on this notification too.
|
||
Task { @MainActor in
|
||
remeasureRowsWhoseThumbnailChanged()
|
||
// Thumbnails that couldn’t download while offline try again.
|
||
if ThumbnailDownloader.shared.networkAllowsDownloads {
|
||
reloadVisibleCells()
|
||
}
|
||
}
|
||
}
|
||
|
||
@objc func handleTimelineShowSeparatorsDidChange(_ notification: Notification) {
|
||
updateGridStyle()
|
||
}
|
||
|
||
@objc func handleTimelineThumbnailsDisplayDidChange(_ notification: Notification) {
|
||
thumbnailsDisplay = AppDefaults.timelineThumbnailsDisplay
|
||
}
|
||
|
||
@objc func handleTimelineFeedIconsDisplayDidChange(_ notification: Notification) {
|
||
updateShowIcons()
|
||
if showIcons {
|
||
IconImageCache.shared.prefetchImagesForArticles(articles)
|
||
}
|
||
performBlockAndRestoreSelection {
|
||
tableView.reloadData()
|
||
}
|
||
}
|
||
|
||
@objc func handleTimelineTextSizeDidChange(_ notification: Notification) {
|
||
textSize = AppDefaults.timelineTextSize
|
||
}
|
||
|
||
@objc func handleTimelineNumberOfLinesDidChange(_ notification: Notification) {
|
||
numberOfLines = AppDefaults.timelineNumberOfLines
|
||
}
|
||
|
||
@objc func handleTimelineShowFullTitlesDidChange(_ notification: Notification) {
|
||
showFullTitles = AppDefaults.timelineShowFullTitles
|
||
}
|
||
|
||
@objc func handleTimelineFeedNameAndDateAboveTitleDidChange(_ notification: Notification) {
|
||
feedNameAndDateAboveTitle = AppDefaults.timelineFeedNameAndDateAboveTitle
|
||
}
|
||
|
||
@objc func handleTimelineFadeReadArticlesDidChange(_ notification: Notification) {
|
||
fadesReadArticles = AppDefaults.timelineFadeReadArticles
|
||
}
|
||
|
||
@objc func handleTimelineIconSizeDidChange(_ notification: Notification) {
|
||
updateCellAppearances()
|
||
rowHeights.removeAll()
|
||
performBlockAndRestoreSelection {
|
||
tableView.reloadData()
|
||
}
|
||
}
|
||
|
||
@objc func accountDidDownloadArticles(_ note: Notification) {
|
||
guard let feeds = note.userInfo?[Account.UserInfoKey.feeds] as? Set<Feed> else {
|
||
return
|
||
}
|
||
|
||
let shouldFetchAndMergeArticles = representedObjectsContainsAnyFeed(feeds) || representedObjectsContainsAnyPseudoFeed()
|
||
if shouldFetchAndMergeArticles {
|
||
queueFetchAndMergeArticles()
|
||
}
|
||
}
|
||
|
||
@objc func accountStateDidChange(_ note: Notification) {
|
||
if representedObjectsContainsAnyPseudoFeed() {
|
||
fetchAndReplacePreservingSelectionAsync()
|
||
}
|
||
}
|
||
|
||
@objc func accountsDidChange(_ note: Notification) {
|
||
if representedObjectsContainsAnyPseudoFeed() {
|
||
fetchAndReplacePreservingSelectionAsync()
|
||
}
|
||
}
|
||
|
||
@objc func userDidDeleteAccount(_ note: Notification) {
|
||
undoManager?.removeAllActions() // Undo stack may contain actions for the deleted account.
|
||
if representedObjectsContainsAnyPseudoFeed() {
|
||
fetchAndReplacePreservingSelectionAsync()
|
||
}
|
||
}
|
||
|
||
@objc func handleSidebarDidAcceptDrop(_ note: Notification) {
|
||
// Drops aren't undoable — without this, ⌘Z could silently undo an older, unrelated action.
|
||
// <https://github.com/Ranchero-Software/NetNewsWire/issues/3583>
|
||
undoManager?.removeAllActions()
|
||
}
|
||
|
||
@objc func containerChildrenDidChange(_ note: Notification) {
|
||
if representedObjectsContainsAnyPseudoFeed() || representedObjectsContainAnyFolder() {
|
||
// Merge, don't replace — replacing drops articles read this session
|
||
// from All Unread. Matches iOS.
|
||
// <https://github.com/Ranchero-Software/NetNewsWire/issues/3832>
|
||
queueFetchAndMergeArticles()
|
||
}
|
||
}
|
||
|
||
/// Separators between rows, never in column layout. `TimelineTableRowView` draws them.
|
||
private func updateGridStyle() {
|
||
let showsSeparators = layout == .standard && AppDefaults.timelineShowSeparators
|
||
let gridStyleMask: NSTableView.GridLineStyle = showsSeparators ? .solidHorizontalGridLineMask : []
|
||
if tableView.gridStyleMask != gridStyleMask {
|
||
tableView.gridStyleMask = gridStyleMask
|
||
}
|
||
}
|
||
|
||
/// The one place the row height is set. In standard layout, it’s the estimate for rows not yet measured.
|
||
func updateTableViewRowHeight() {
|
||
tableView.rowHeight = layout == .column ? columnRowHeight() : estimatedRowHeight
|
||
}
|
||
|
||
// MARK: - Reloading Data
|
||
|
||
private func cellForRowView(_ rowView: NSView) -> NSView? {
|
||
for oneView in rowView.subviews where oneView is TimelineTableCellView {
|
||
return oneView
|
||
}
|
||
return nil
|
||
}
|
||
|
||
private func reloadVisibleCells() {
|
||
guard let indexes = tableView.indexesOfAvailableRows() else {
|
||
return
|
||
}
|
||
reloadVisibleCells(for: indexes)
|
||
}
|
||
|
||
private func reloadVisibleCells(for articles: [Article]) {
|
||
reloadVisibleCells(for: Set(articles.articleIDs()))
|
||
}
|
||
|
||
private func reloadVisibleCells(for articles: Set<Article>) {
|
||
reloadVisibleCells(for: articles.articleIDs())
|
||
}
|
||
|
||
private func reloadVisibleCells(for articleIDs: Set<String>) {
|
||
if articleIDs.isEmpty {
|
||
return
|
||
}
|
||
let indexes = indexesForArticleIDs(articleIDs)
|
||
reloadVisibleCells(for: indexes)
|
||
}
|
||
|
||
private func reloadVisibleCells(for indexes: IndexSet) {
|
||
let indexesToReload = tableView.indexesOfAvailableRowsPassingTest { (row) -> Bool in
|
||
return indexes.contains(row)
|
||
}
|
||
if let indexesToReload = indexesToReload {
|
||
reloadCells(for: indexesToReload)
|
||
}
|
||
}
|
||
|
||
private func reloadCells(for indexes: IndexSet) {
|
||
if indexes.isEmpty {
|
||
return
|
||
}
|
||
tableView.reloadData(forRowIndexes: indexes, columnIndexes: IndexSet(integersIn: 0..<tableView.numberOfColumns))
|
||
}
|
||
|
||
// MARK: - Cell Configuring
|
||
|
||
/// The full number of lines, with no icon or thumbnail.
|
||
private func calculateEstimatedRowHeight() -> CGFloat {
|
||
let longTitle = "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
|
||
let prototypeID = "prototype"
|
||
let status = ArticleStatus(articleID: prototypeID, read: false, starred: false, dateArrived: Date())
|
||
let prototypeArticle = Article(accountID: prototypeID, articleID: prototypeID, feedID: prototypeID, uniqueID: prototypeID, title: longTitle, contentHTML: nil, contentText: nil, markdown: nil, url: nil, externalURL: nil, summary: nil, imageURL: nil, thumbnailURL: nil, datePublished: nil, dateModified: nil, authors: nil, attachments: nil, status: status)
|
||
|
||
let prototypeCellData = TimelineCellData(article: prototypeArticle, showFeedName: .feed, feedName: "Prototype Feed Name", byline: nil, iconImage: nil, showIcon: false, thumbnail: nil, showThumbnail: false)
|
||
return TimelineCellLayout.height(for: Self.prototypeRowWidth, cellData: prototypeCellData, appearance: cellAppearance)
|
||
}
|
||
|
||
private func updateEstimatedRowHeight() {
|
||
estimatedRowHeight = calculateEstimatedRowHeight()
|
||
updateTableViewRowHeight()
|
||
}
|
||
|
||
// MARK: - Row Heights
|
||
|
||
/// Nil when the row hasn’t been measured, or its article changed since.
|
||
private func measuredRowHeight(for article: Article) -> CGFloat? {
|
||
guard let rowHeight = rowHeights[ArticleIdentityKey(article)], rowHeight.article === article else {
|
||
return nil
|
||
}
|
||
return rowHeight.height
|
||
}
|
||
|
||
private func measureRowHeight(for article: Article) {
|
||
let showThumbnail = articleShowsThumbnail(article)
|
||
let cellData = TimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.feed?.nameForDisplay, byline: article.byline(), iconImage: nil, showIcon: showIcons, thumbnail: nil, showThumbnail: showThumbnail)
|
||
let appearance: TimelineCellAppearance = showIcons ? cellAppearanceWithIcon : cellAppearance
|
||
let height = TimelineCellLayout.height(for: rowHeightWidth, cellData: cellData, appearance: appearance)
|
||
rowHeights[ArticleIdentityKey(article)] = TimelineRowHeight(article: article, showsThumbnail: showThumbnail, height: height)
|
||
}
|
||
|
||
private func articleShowsThumbnail(_ article: Article) -> Bool {
|
||
guard let thumbnailMode else {
|
||
return false
|
||
}
|
||
return ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) != nil
|
||
}
|
||
|
||
/// Measures right away when there are few rows, so they don’t show the estimate first.
|
||
private func remeasureRowHeights(_ rows: IndexSet) {
|
||
guard layout == .standard, !rows.isEmpty else {
|
||
return
|
||
}
|
||
let measuresNow = rows.count <= Self.rowHeightBatchSize && rowHeightWidth > 0.0
|
||
for row in rows {
|
||
guard let article = articles.articleAtRow(row) else {
|
||
continue
|
||
}
|
||
rowHeights[ArticleIdentityKey(article)] = nil
|
||
if measuresNow {
|
||
measureRowHeight(for: article)
|
||
}
|
||
}
|
||
noteHeightOfRowsKeepingScrollPosition(rows)
|
||
}
|
||
|
||
/// `oldArticles` are the same articles in the same order. A changed article is a new instance.
|
||
private func rowsWithChangedArticles(comparedWith oldArticles: ArticleArray) -> IndexSet {
|
||
var rows = IndexSet()
|
||
for (row, (oldArticle, article)) in zip(oldArticles, articles).enumerated() where oldArticle !== article {
|
||
rows.insert(row)
|
||
}
|
||
return rows
|
||
}
|
||
|
||
/// For thumbnail choices that change with no failure notification, such as after a network change.
|
||
private func remeasureRowsWhoseThumbnailChanged() {
|
||
var rows = IndexSet()
|
||
for (row, article) in articles.enumerated() {
|
||
if let rowHeight = rowHeights[ArticleIdentityKey(article)], rowHeight.showsThumbnail != articleShowsThumbnail(article) {
|
||
rows.insert(row)
|
||
}
|
||
}
|
||
remeasureRowHeights(rows)
|
||
}
|
||
|
||
private func removeRowHeightsForMissingArticles() {
|
||
let articleKeys = Set(articles.map { ArticleIdentityKey($0) })
|
||
rowHeights = rowHeights.filter { articleKeys.contains($0.key) }
|
||
}
|
||
|
||
/// A width change makes every height stale. Rows near the visible ones are measured during layout, the rest in passes.
|
||
private func updateRowHeightWidth() {
|
||
let width = standardCellWidth()
|
||
guard width > 0.0, width != rowHeightWidth else {
|
||
return
|
||
}
|
||
rowHeightWidth = width
|
||
rowHeights.removeAll()
|
||
scheduleRowHeightMeasuring(from: 0)
|
||
}
|
||
|
||
/// A shown cell’s width when there is one. Otherwise the width the table gives cells.
|
||
private func standardCellWidth() -> CGFloat {
|
||
let visibleRows = tableView.rows(in: tableView.visibleRect)
|
||
if visibleRows.length > 0, let cell = tableView.view(atColumn: 0, row: visibleRows.location, makeIfNecessary: false) {
|
||
return cell.frame.width
|
||
}
|
||
if tableView.numberOfRows > 0 {
|
||
return tableView.frameOfCell(atColumn: 0, row: 0).width
|
||
}
|
||
guard let column = tableView.tableColumns.first else {
|
||
return 0.0
|
||
}
|
||
return column.width - tableView.intercellSpacing.width
|
||
}
|
||
|
||
/// The visible rows plus a screenful above and below, so scrolling a little doesn’t show estimates.
|
||
private func measureRowHeightsNearVisibleRows() {
|
||
guard rowHeightWidth > 0.0 else {
|
||
return
|
||
}
|
||
let visibleRect = tableView.visibleRect
|
||
let nearbyRows = tableView.rows(in: visibleRect.insetBy(dx: 0.0, dy: -visibleRect.height))
|
||
guard nearbyRows.length > 0 else {
|
||
return
|
||
}
|
||
var measuredRows = IndexSet()
|
||
for row in nearbyRows.location..<NSMaxRange(nearbyRows) {
|
||
guard let article = articles.articleAtRow(row), measuredRowHeight(for: article) == nil else {
|
||
continue
|
||
}
|
||
measureRowHeight(for: article)
|
||
measuredRows.insert(row)
|
||
}
|
||
if !measuredRows.isEmpty {
|
||
noteHeightOfRowsKeepingScrollPosition(measuredRows)
|
||
}
|
||
}
|
||
|
||
private func scheduleRowHeightMeasuring(from row: Int) {
|
||
rowHeightMeasuringStartRow = min(rowHeightMeasuringStartRow ?? row, row)
|
||
guard !isRowHeightMeasuringScheduled else {
|
||
return
|
||
}
|
||
isRowHeightMeasuringScheduled = true
|
||
Task { @MainActor [weak self] in
|
||
self?.measureNextRowHeightBatch()
|
||
}
|
||
}
|
||
|
||
/// Measures up to `rowHeightBatchSize` rows per pass, so a large timeline doesn’t block the main thread.
|
||
/// Waits during live resize, when only rows near the visible ones are measured.
|
||
private func measureNextRowHeightBatch() {
|
||
isRowHeightMeasuringScheduled = false
|
||
guard let startRow = rowHeightMeasuringStartRow, layout == .standard, rowHeightWidth > 0.0, !tableView.inLiveResize else {
|
||
return
|
||
}
|
||
rowHeightMeasuringStartRow = nil
|
||
|
||
var measuredRows = IndexSet()
|
||
var row = startRow
|
||
while row < articles.count && measuredRows.count < Self.rowHeightBatchSize {
|
||
let article = articles[row]
|
||
if measuredRowHeight(for: article) == nil {
|
||
measureRowHeight(for: article)
|
||
measuredRows.insert(row)
|
||
}
|
||
row += 1
|
||
}
|
||
|
||
if !measuredRows.isEmpty {
|
||
noteHeightOfRowsKeepingScrollPosition(measuredRows)
|
||
}
|
||
if row < articles.count {
|
||
scheduleRowHeightMeasuring(from: row)
|
||
}
|
||
}
|
||
|
||
/// Keeps the top visible row in place when rows above it change height.
|
||
private func noteHeightOfRowsKeepingScrollPosition(_ rowIndexes: IndexSet) {
|
||
guard let scrollView = tableView.enclosingScrollView else {
|
||
noteHeightOfRowsWithoutAnimation(rowIndexes)
|
||
return
|
||
}
|
||
let clipView = scrollView.contentView
|
||
let topY = clipView.bounds.minY
|
||
let topRow = tableView.row(at: NSPoint(x: 0, y: max(topY, 0)))
|
||
guard topRow > 0, let firstChangedRow = rowIndexes.first, firstChangedRow < topRow else {
|
||
noteHeightOfRowsWithoutAnimation(rowIndexes)
|
||
return
|
||
}
|
||
|
||
let offsetIntoTopRow = topY - tableView.rect(ofRow: topRow).minY
|
||
noteHeightOfRowsWithoutAnimation(rowIndexes)
|
||
clipView.scroll(to: NSPoint(x: clipView.bounds.minX, y: tableView.rect(ofRow: topRow).minY + offsetIntoTopRow))
|
||
scrollView.reflectScrolledClipView(clipView)
|
||
}
|
||
|
||
private func noteHeightOfRowsWithoutAnimation(_ rowIndexes: IndexSet) {
|
||
NSAnimationContext.runAnimationGroup { context in
|
||
context.duration = 0
|
||
tableView.noteHeightOfRows(withIndexesChanged: rowIndexes)
|
||
}
|
||
}
|
||
|
||
@objc func fetchAndMergeArticles() {
|
||
guard let representedObjects = representedObjects else {
|
||
return
|
||
}
|
||
|
||
fetchUnsortedArticlesAsync(for: representedObjects) { [weak self] (unsortedArticles) in
|
||
// Merge articles by articleID. For any unique articleID in current articles, add to unsortedArticles.
|
||
guard let strongSelf = self else {
|
||
return
|
||
}
|
||
let unsortedArticleIDs = unsortedArticles.articleIDs()
|
||
var updatedArticles = unsortedArticles
|
||
for article in strongSelf.articles {
|
||
if !unsortedArticleIDs.contains(article.articleID) {
|
||
updatedArticles.insert(article)
|
||
}
|
||
}
|
||
strongSelf.performBlockAndRestoreSelection {
|
||
strongSelf.replaceArticles(with: updatedArticles)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - NSMenuDelegate
|
||
|
||
extension TimelineViewController: NSMenuDelegate {
|
||
|
||
public func menuNeedsUpdate(_ menu: NSMenu) {
|
||
menu.removeAllItems()
|
||
guard let contextualMenu = contextualMenuForClickedRows() else {
|
||
return
|
||
}
|
||
menu.takeItems(from: contextualMenu)
|
||
}
|
||
}
|
||
|
||
// MARK: - NSUserInterfaceValidations
|
||
|
||
extension TimelineViewController: NSUserInterfaceValidations {
|
||
|
||
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
|
||
if item.action == #selector(openArticleInBrowser(_:)) {
|
||
if let item = item as? NSMenuItem, item.keyEquivalentModifierMask.contains(.shift) {
|
||
item.title = Browser.titleForOpenInBrowserInverted
|
||
}
|
||
|
||
let currentLink = oneSelectedArticle?.preferredLink
|
||
return currentLink != nil
|
||
}
|
||
|
||
if item.action == #selector(copy(_:)) {
|
||
return NSPasteboard.general.canCopyAtLeastOneObject(selectedArticles)
|
||
}
|
||
|
||
return true
|
||
}
|
||
}
|
||
|
||
// MARK: - NSTableViewDataSource
|
||
|
||
extension TimelineViewController: NSTableViewDataSource {
|
||
func numberOfRows(in tableView: NSTableView) -> Int {
|
||
return articles.count
|
||
}
|
||
|
||
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
|
||
return articles.articleAtRow(row) ?? nil
|
||
}
|
||
|
||
func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? {
|
||
guard let article = articles.articleAtRow(row) else {
|
||
return nil
|
||
}
|
||
return ArticlePasteboardWriter(article: article)
|
||
}
|
||
|
||
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
|
||
// Keeping -[NSTableViewDelegate tableView:heightOfRow:] implemented fixes
|
||
// an issue that the bottom inset of NSTableView disappears on macOS Monterey.
|
||
guard layout == .standard, let article = articles.articleAtRow(row) else {
|
||
return tableView.rowHeight
|
||
}
|
||
if let height = measuredRowHeight(for: article) {
|
||
return height
|
||
}
|
||
scheduleRowHeightMeasuring(from: row)
|
||
return tableView.rowHeight
|
||
}
|
||
}
|
||
|
||
// MARK: - TimelineTableViewRowHeightDelegate
|
||
|
||
extension TimelineViewController: TimelineTableViewRowHeightDelegate {
|
||
|
||
func timelineTableViewDidLayout(_ tableView: TimelineTableView) {
|
||
guard layout == .standard else {
|
||
return
|
||
}
|
||
updateRowHeightWidth()
|
||
measureRowHeightsNearVisibleRows()
|
||
}
|
||
|
||
func timelineTableViewDidEndLiveResize(_ tableView: TimelineTableView) {
|
||
if let rowHeightMeasuringStartRow {
|
||
scheduleRowHeightMeasuring(from: rowHeightMeasuringStartRow)
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - NSTableViewDelegate
|
||
|
||
extension TimelineViewController: NSTableViewDelegate {
|
||
private static let rowViewIdentifier = NSUserInterfaceItemIdentifier(rawValue: "timelineRow")
|
||
|
||
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
|
||
if layout == .column {
|
||
// The standard row view suits column layout. TimelineTableRowView only knows the standard cell.
|
||
return nil
|
||
}
|
||
let rowView: TimelineTableRowView
|
||
if let reusedRowView = tableView.makeView(withIdentifier: TimelineViewController.rowViewIdentifier, owner: nil) as? TimelineTableRowView {
|
||
rowView = reusedRowView
|
||
} else {
|
||
rowView = TimelineTableRowView()
|
||
rowView.identifier = TimelineViewController.rowViewIdentifier
|
||
}
|
||
// Rows change only by reloading, which asks for every row view again, so a former last row doesn’t keep this.
|
||
rowView.isLastRow = row == tableView.numberOfRows - 1
|
||
return rowView
|
||
}
|
||
|
||
private static let timelineCellIdentifier = NSUserInterfaceItemIdentifier(rawValue: "timelineCell")
|
||
|
||
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
|
||
let cellView = layout == .column ? columnCellView(for: tableColumn, row: row) : standardCellView(for: row)
|
||
if let cellView {
|
||
applyReadFading(to: cellView, row: row)
|
||
}
|
||
return cellView
|
||
}
|
||
|
||
private func standardCellView(for row: Int) -> NSView {
|
||
func configure(_ cell: TimelineTableCellView) {
|
||
cell.cellAppearance = showIcons ? cellAppearanceWithIcon : cellAppearance
|
||
if let article = articles.articleAtRow(row) {
|
||
configureTimelineCell(cell, article: article)
|
||
if measuredRowHeight(for: article) == nil {
|
||
// Measured after layout, before it draws.
|
||
tableView.needsLayout = true
|
||
}
|
||
} else {
|
||
makeTimelineCellEmpty(cell)
|
||
}
|
||
}
|
||
|
||
if let cell = tableView.makeView(withIdentifier: TimelineViewController.timelineCellIdentifier, owner: nil) as? TimelineTableCellView {
|
||
configure(cell)
|
||
return cell
|
||
}
|
||
|
||
let cell = TimelineTableCellView()
|
||
cell.identifier = TimelineViewController.timelineCellIdentifier
|
||
configure(cell)
|
||
return cell
|
||
}
|
||
|
||
func tableViewSelectionDidChange(_ notification: Notification) {
|
||
applyReadFadingToAvailableRows()
|
||
|
||
if selectedArticles.isEmpty {
|
||
selectionDidChange(nil)
|
||
return
|
||
}
|
||
|
||
if selectedArticles.count == 1 {
|
||
let article = selectedArticles.first!
|
||
if !article.status.read {
|
||
markArticles(Set([article]), statusKey: .read, flag: true)
|
||
}
|
||
}
|
||
|
||
selectionDidChange(selectedArticles)
|
||
}
|
||
|
||
private func selectionDidChange(_ selectedArticles: ArticleArray?) {
|
||
// Compare by identity, not content — re-pushing an updated article that the user is reading
|
||
// would reset the article view scroll position.
|
||
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5387>
|
||
let selectedArticleKeys = selectedArticles?.map { ArticleIdentityKey($0) }
|
||
guard selectedArticleKeys != previouslySelectedArticleKeys else {
|
||
return
|
||
}
|
||
previouslySelectedArticleKeys = selectedArticleKeys
|
||
delegate?.timelineSelectionDidChange(self, selectedArticles: selectedArticles)
|
||
delegate?.timelineInvalidatedRestorationState(self)
|
||
}
|
||
|
||
private func configureTimelineCell(_ cell: TimelineTableCellView, article: Article) {
|
||
cell.objectValue = article
|
||
let iconImage = showIcons ? article.iconImage() : nil
|
||
var thumbnail: NSImage?
|
||
var showThumbnail = false
|
||
if let thumbnailMode, let thumbnailURL = ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) {
|
||
showThumbnail = true
|
||
thumbnail = ThumbnailDownloader.shared.thumbnail(url: thumbnailURL, mode: thumbnailMode, feedName: article.feed?.nameForDisplay, articleTitle: article.title)
|
||
}
|
||
cell.cellData = TimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.feed?.nameForDisplay, byline: article.byline(), iconImage: iconImage, showIcon: showIcons, thumbnail: thumbnail, showThumbnail: showThumbnail)
|
||
}
|
||
|
||
/// Fades the cell views, not the row view, so the selection highlight and separators stay full strength.
|
||
/// The selected row never fades, since selecting an article marks it read.
|
||
private func applyReadFading(to cellView: NSView, row: Int) {
|
||
var alphaValue: CGFloat = 1.0
|
||
if fadesReadArticles, let article = articles.articleAtRow(row), article.status.read, !tableView.isRowSelected(row) {
|
||
alphaValue = Self.readArticleAlphaValue
|
||
}
|
||
if cellView.alphaValue != alphaValue {
|
||
cellView.alphaValue = alphaValue
|
||
}
|
||
}
|
||
|
||
/// Selection changes don’t reload cells.
|
||
private func applyReadFadingToAvailableRows() {
|
||
tableView.enumerateAvailableRowViews { rowView, row in
|
||
for column in 0..<rowView.numberOfColumns {
|
||
if let cellView = rowView.view(atColumn: column) as? NSView {
|
||
applyReadFading(to: cellView, row: row)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
private func makeTimelineCellEmpty(_ cell: TimelineTableCellView) {
|
||
cell.objectValue = nil
|
||
cell.cellData = TimelineCellData()
|
||
}
|
||
|
||
private func toggleArticleRead(_ article: Article) {
|
||
guard let undoManager = undoManager, let markUnreadCommand = MarkStatusCommand(initialArticles: [article], markingRead: !article.status.read, undoManager: undoManager) else {
|
||
return
|
||
}
|
||
self.runCommand(markUnreadCommand)
|
||
}
|
||
|
||
private func toggleArticleStarred(_ article: Article) {
|
||
guard let undoManager = undoManager, let markUnreadCommand = MarkStatusCommand(initialArticles: [article], markingStarred: !article.status.starred, undoManager: undoManager) else {
|
||
return
|
||
}
|
||
self.runCommand(markUnreadCommand)
|
||
}
|
||
|
||
func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] {
|
||
|
||
guard let article = articles.articleAtRow(row) else {
|
||
return []
|
||
}
|
||
|
||
switch edge {
|
||
case .leading:
|
||
let action = NSTableViewRowAction(style: .regular, title: article.status.read ? "Unread" : "Read") { (_, _) in
|
||
self.toggleArticleRead(article)
|
||
tableView.rowActionsVisible = false
|
||
}
|
||
action.image = article.status.read ? Assets.Images.swipeMarkUnread : Assets.Images.swipeMarkRead
|
||
return [action]
|
||
|
||
case .trailing:
|
||
let action = NSTableViewRowAction(style: .regular, title: article.status.starred ? "Unstar" : "Star") { (_, _) in
|
||
self.toggleArticleStarred(article)
|
||
tableView.rowActionsVisible = false
|
||
}
|
||
action.backgroundColor = Assets.Colors.star
|
||
action.image = article.status.starred ? Assets.Images.swipeMarkUnstarred : Assets.Images.swipeMarkStarred
|
||
return [action]
|
||
|
||
@unknown default:
|
||
Self.logger.error("TimelineViewController: unknown edge \(edge.rawValue, privacy: .public)")
|
||
}
|
||
|
||
return []
|
||
}
|
||
}
|
||
|
||
// MARK: - Private
|
||
|
||
private extension TimelineViewController {
|
||
|
||
/// The table doesn’t shrink by itself when the pane narrows after leaving column layout.
|
||
func fitTableViewToVisibleWidthInStandardLayout() {
|
||
guard layout == .standard, let scrollView = tableView.enclosingScrollView else {
|
||
return
|
||
}
|
||
let contentInsets = scrollView.contentInsets
|
||
let visibleWidth = scrollView.contentView.bounds.width - contentInsets.left - contentInsets.right
|
||
guard visibleWidth > 0, tableView.frame.width != visibleWidth else {
|
||
return
|
||
}
|
||
tableView.setFrameSize(NSSize(width: visibleWidth, height: tableView.frame.height))
|
||
tableView.sizeLastColumnToFit()
|
||
}
|
||
|
||
/// Returns true if it scrolled. Callers should skip further scrolling then,
|
||
/// since the animation hasn’t updated the visible rect yet.
|
||
/// <https://github.com/Ranchero-Software/NetNewsWire/issues/5486>
|
||
@discardableResult func scrollToRowIfNotFullyVisible(_ row: Int) -> Bool {
|
||
guard (0..<tableView.numberOfRows).contains(row), !tableView.isRowFullyVisible(row) else {
|
||
return false
|
||
}
|
||
tableView.scrollRowFullyIntoView(row)
|
||
return true
|
||
}
|
||
|
||
func fetchAndReplacePreservingSelection() {
|
||
if let article = oneSelectedArticle, let account = article.account {
|
||
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: article.articleID)
|
||
}
|
||
performBlockAndRestoreSelection {
|
||
fetchAndReplaceArticlesSync()
|
||
}
|
||
}
|
||
|
||
// The current article should stay in the timeline, and stay selected,
|
||
// when the timeline updates and the sidebar selection hasn't changed —
|
||
// even if the new fetch wouldn't otherwise include it.
|
||
func fetchAndReplacePreservingSelectionAsync() {
|
||
if let article = oneSelectedArticle, let account = article.account {
|
||
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: article.articleID)
|
||
}
|
||
let savedSelection = selectedArticleIDs()
|
||
fetchAndReplaceArticlesAsync { [weak self] in
|
||
self?.restoreSelection(savedSelection)
|
||
}
|
||
}
|
||
|
||
func updateUnreadCount() {
|
||
var count = 0
|
||
for article in articles {
|
||
if !article.status.read {
|
||
count += 1
|
||
}
|
||
}
|
||
unreadCount = count
|
||
}
|
||
|
||
func layoutDidChange() {
|
||
rowHeights.removeAll()
|
||
performBlockAndRestoreSelection {
|
||
configureTableView(for: layout)
|
||
updateGridStyle()
|
||
updateShowIcons()
|
||
tableView.reloadData()
|
||
}
|
||
if tableView.selectedRow != -1 {
|
||
tableView.scrollRowToVisible(tableView.selectedRow)
|
||
}
|
||
}
|
||
|
||
func updateShowIcons() {
|
||
switch AppDefaults.timelineFeedIconsDisplay {
|
||
case .always:
|
||
self.showIcons = true
|
||
return
|
||
case .never:
|
||
self.showIcons = false
|
||
return
|
||
case .automatic:
|
||
break
|
||
}
|
||
|
||
if layout == .column {
|
||
// With Automatic, the Feed column shows the feed icon.
|
||
self.showIcons = true
|
||
return
|
||
}
|
||
|
||
if showFeedNames == .feed {
|
||
self.showIcons = true
|
||
return
|
||
}
|
||
|
||
if showFeedNames == .none {
|
||
self.showIcons = false
|
||
return
|
||
}
|
||
|
||
for article in articles {
|
||
if let authors = article.authors {
|
||
for author in authors {
|
||
if author.avatarURL != nil {
|
||
self.showIcons = true
|
||
return
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
self.showIcons = false
|
||
}
|
||
|
||
func emptyTheTimeline() {
|
||
if !articles.isEmpty {
|
||
articles = [Article]()
|
||
}
|
||
}
|
||
|
||
func sortParametersDidChange() {
|
||
performBlockAndRestoreSelection {
|
||
let unsortedArticles = Set(articles)
|
||
replaceArticles(with: unsortedArticles)
|
||
}
|
||
}
|
||
|
||
func selectedArticleIDs() -> [String] {
|
||
return selectedArticles.articleIDs()
|
||
}
|
||
|
||
func restoreSelection(_ articleIDs: [String]) {
|
||
selectArticles(articleIDs)
|
||
if tableView.selectedRow != -1 {
|
||
tableView.scrollRowToVisible(tableView.selectedRow)
|
||
}
|
||
}
|
||
|
||
func performBlockAndRestoreSelection(_ block: (() -> Void)) {
|
||
let savedSelection = selectedArticleIDs()
|
||
block()
|
||
restoreSelection(savedSelection)
|
||
}
|
||
|
||
func rows(for articleID: String) -> [Int]? {
|
||
updateArticleRowMapIfNeeded()
|
||
return articleRowMap[articleID]
|
||
}
|
||
|
||
func rows(for article: Article) -> [Int]? {
|
||
return rows(for: article.articleID)
|
||
}
|
||
|
||
func updateArticleRowMap() {
|
||
var rowMap = [String: [Int]]()
|
||
var index = 0
|
||
for article in articles {
|
||
if var indexes = rowMap[article.articleID] {
|
||
indexes.append(index)
|
||
rowMap[article.articleID] = indexes
|
||
} else {
|
||
rowMap[article.articleID] = [index]
|
||
}
|
||
index += 1
|
||
}
|
||
articleRowMap = rowMap
|
||
}
|
||
|
||
func updateArticleRowMapIfNeeded() {
|
||
if articleRowMap.isEmpty {
|
||
updateArticleRowMap()
|
||
}
|
||
}
|
||
|
||
func indexesForArticleIDs(_ articleIDs: Set<String>) -> IndexSet {
|
||
var indexes = IndexSet()
|
||
|
||
for articleID in articleIDs {
|
||
guard let rowsIndex = rows(for: articleID) else {
|
||
continue
|
||
}
|
||
for rowIndex in rowsIndex {
|
||
indexes.insert(rowIndex)
|
||
}
|
||
}
|
||
|
||
return indexes
|
||
}
|
||
|
||
// MARK: - Thumbnails
|
||
|
||
/// Updates row heights and visible cells.
|
||
func thumbnailURLsDidChange(for articleIDs: Set<String>) {
|
||
guard !articleIDs.isEmpty else {
|
||
return
|
||
}
|
||
if thumbnailMode != nil {
|
||
remeasureRowHeights(indexesForArticleIDs(articleIDs))
|
||
}
|
||
reloadVisibleCells(for: articleIDs)
|
||
}
|
||
|
||
func thumbnailsDisplayDidChange() {
|
||
updateCellAppearances()
|
||
rowHeights.removeAll()
|
||
guard layout == .standard else {
|
||
return
|
||
}
|
||
performBlockAndRestoreSelection {
|
||
tableView.reloadData()
|
||
}
|
||
if tableView.selectedRow != -1 {
|
||
tableView.scrollRowToVisible(tableView.selectedRow)
|
||
}
|
||
}
|
||
|
||
// MARK: - Appearance Change
|
||
|
||
private func updateCellAppearances() {
|
||
let iconSize = AppDefaults.timelineIconSize
|
||
cellAppearance = TimelineCellAppearance(showIcon: false, textSize: textSize, iconSize: iconSize, numberOfLines: numberOfLines, showsFullTitles: showFullTitles, feedNameAndDateAboveTitle: feedNameAndDateAboveTitle, showsLargeThumbnails: thumbnailsDisplay == .large)
|
||
cellAppearanceWithIcon = TimelineCellAppearance(showIcon: true, textSize: textSize, iconSize: iconSize, numberOfLines: numberOfLines, showsFullTitles: showFullTitles, feedNameAndDateAboveTitle: feedNameAndDateAboveTitle, showsLargeThumbnails: thumbnailsDisplay == .large)
|
||
}
|
||
|
||
private func cellAppearanceSettingDidChange() {
|
||
updateCellAppearances()
|
||
updateEstimatedRowHeight()
|
||
rowHeights.removeAll()
|
||
performBlockAndRestoreSelection {
|
||
tableView.reloadData()
|
||
}
|
||
}
|
||
|
||
// MARK: - Fetching Articles
|
||
|
||
func fetchAndReplaceArticlesSync() {
|
||
// To be called when the user has made a change of selection in the sidebar.
|
||
// It blocks the main thread, so that there’s no async delay,
|
||
// so that the entire display refreshes at once.
|
||
// It’s a better user experience this way.
|
||
cancelPendingAsyncFetches()
|
||
guard var representedObjects = representedObjects else {
|
||
emptyTheTimeline()
|
||
return
|
||
}
|
||
|
||
if exceptionArticleFetcher != nil {
|
||
representedObjects.append(exceptionArticleFetcher as AnyObject)
|
||
exceptionArticleFetcher = nil
|
||
}
|
||
|
||
let fetchedArticles = fetchUnsortedArticlesSync(for: representedObjects)
|
||
replaceArticles(with: fetchedArticles)
|
||
}
|
||
|
||
func fetchAndReplaceArticlesAsync(completion: (() -> Void)? = nil) {
|
||
// To be called when we need to do an entire fetch, but an async delay is okay.
|
||
// Example: we have the Today feed selected, and the calendar day just changed.
|
||
cancelPendingAsyncFetches()
|
||
guard var representedObjects = representedObjects else {
|
||
emptyTheTimeline()
|
||
return
|
||
}
|
||
|
||
if exceptionArticleFetcher != nil {
|
||
representedObjects.append(exceptionArticleFetcher as AnyObject)
|
||
exceptionArticleFetcher = nil
|
||
}
|
||
|
||
fetchUnsortedArticlesAsync(for: representedObjects) { [weak self] (articles) in
|
||
self?.replaceArticles(with: articles)
|
||
completion?()
|
||
}
|
||
}
|
||
|
||
func cancelPendingAsyncFetches() {
|
||
fetchSerialNumber += 1
|
||
fetchRequestQueue.cancelAllRequests()
|
||
}
|
||
|
||
func replaceArticles(with unsortedArticles: Set<Article>) {
|
||
articles = Array(unsortedArticles).sorted(by: sortParameters)
|
||
}
|
||
|
||
func fetchUnsortedArticlesSync(for representedObjects: [Any]) -> Set<Article> {
|
||
cancelPendingAsyncFetches()
|
||
let fetchers = representedObjects.compactMap { $0 as? ArticleFetcher }
|
||
if fetchers.isEmpty {
|
||
return Set<Article>()
|
||
}
|
||
|
||
var fetchedArticles = Set<Article>()
|
||
for fetchers in fetchers {
|
||
if (fetchers as? SidebarItem)?.readFiltered(readFilterEnabledTable: readFilterEnabledTable) ?? true {
|
||
let articles = fetchers.fetchUnreadArticles()
|
||
fetchedArticles.formUnion(articles)
|
||
} else {
|
||
let articles = fetchers.fetchArticles()
|
||
fetchedArticles.formUnion(articles)
|
||
}
|
||
}
|
||
return fetchedArticles
|
||
}
|
||
|
||
func fetchUnsortedArticlesAsync(for representedObjects: [Any], completion: @escaping ArticleSetBlock) {
|
||
// The callback will *not* be called if the fetch is no longer relevant — that is,
|
||
// if it’s been superseded by a newer fetch, or the timeline was emptied, etc., it won’t get called.
|
||
precondition(Thread.isMainThread)
|
||
cancelPendingAsyncFetches()
|
||
let fetchers = representedObjects.compactMap { $0 as? ArticleFetcher }
|
||
let fetchOperation = FetchRequestOperation(id: fetchSerialNumber, readFilterEnabledTable: readFilterEnabledTable, fetchers: fetchers, findsThumbnailURLs: thumbnailMode != nil) { [weak self] (articles, operation) in
|
||
precondition(Thread.isMainThread)
|
||
guard !operation.isCanceled, let strongSelf = self, operation.id == strongSelf.fetchSerialNumber else {
|
||
return
|
||
}
|
||
completion(articles)
|
||
}
|
||
fetchRequestQueue.add(fetchOperation)
|
||
}
|
||
|
||
func selectArticles(_ articleIDs: [String]) {
|
||
let indexesToSelect = indexesForArticleIDs(Set(articleIDs))
|
||
if indexesToSelect.isEmpty {
|
||
tableView.deselectAll(self)
|
||
return
|
||
}
|
||
tableView.selectRowIndexes(indexesToSelect, byExtendingSelection: false)
|
||
}
|
||
|
||
func queueFetchAndMergeArticles() {
|
||
TimelineViewController.fetchAndMergeArticlesQueue.add(self, #selector(fetchAndMergeArticles))
|
||
}
|
||
|
||
func representedObjectArraysAreEqual(_ objects1: [AnyObject]?, _ objects2: [AnyObject]?) -> Bool {
|
||
if objects1 == nil && objects2 == nil {
|
||
return true
|
||
}
|
||
guard let objects1 = objects1, let objects2 = objects2 else {
|
||
return false
|
||
}
|
||
if objects1.count != objects2.count {
|
||
return false
|
||
}
|
||
|
||
var ix = 0
|
||
for oneObject in objects1 {
|
||
if oneObject !== objects2[ix] {
|
||
return false
|
||
}
|
||
ix += 1
|
||
}
|
||
return true
|
||
}
|
||
|
||
func representedObjectsContainsAnyPseudoFeed() -> Bool {
|
||
return representedObjects?.contains(where: { $0 is PseudoFeed}) ?? false
|
||
}
|
||
|
||
func representedObjectsContainsTodayFeed() -> Bool {
|
||
return representedObjects?.contains(where: { $0 === SmartFeedsController.shared.todayFeed }) ?? false
|
||
}
|
||
|
||
func representedObjectsContainAnyFolder() -> Bool {
|
||
return representedObjects?.contains(where: { $0 is Folder }) ?? false
|
||
}
|
||
|
||
func seedReadFilterForFolders() {
|
||
guard let representedObjects else {
|
||
return
|
||
}
|
||
for object in representedObjects {
|
||
guard let folder = object as? Folder, let sidebarItemID = folder.sidebarItemID else {
|
||
continue
|
||
}
|
||
if readFilterEnabledTable[sidebarItemID] == nil {
|
||
readFilterEnabledTable[sidebarItemID] = true
|
||
}
|
||
}
|
||
}
|
||
|
||
func representedObjectsContainsAnyFeed(_ feeds: Set<Feed>) -> Bool {
|
||
// Return true if there’s a match or if a folder contains (recursively) one of feeds
|
||
|
||
guard let representedObjects = representedObjects else {
|
||
return false
|
||
}
|
||
for representedObject in representedObjects {
|
||
if let feed = representedObject as? Feed {
|
||
for oneFeed in feeds {
|
||
if feed.feedID == oneFeed.feedID || feed.url == oneFeed.url {
|
||
return true
|
||
}
|
||
}
|
||
} else if let folder = representedObject as? Folder {
|
||
for oneFeed in feeds {
|
||
if folder.hasFeed(with: oneFeed.feedID) || folder.hasFeed(withURL: oneFeed.url) {
|
||
return true
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
}
|