mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-11-28 08:17:16 +00:00
1636 lines
53 KiB
Swift
1636 lines
53 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]]()
|
||
if thumbnailMode == .large {
|
||
let rows = rowsThatGainedOrLostThumbnail(comparedWith: oldValue)
|
||
if !rows.isEmpty {
|
||
noteHeightOfRowsKeepingScrollPosition(rows)
|
||
}
|
||
}
|
||
reloadVisibleCells()
|
||
return
|
||
}
|
||
|
||
if let representedObjects = representedObjects, representedObjects.count == 1 && representedObjects.first is Feed {
|
||
showFeedNames = {
|
||
for article in articles {
|
||
if !article.byline().isEmpty {
|
||
return .byline
|
||
}
|
||
}
|
||
return .none
|
||
}()
|
||
} else {
|
||
showFeedNames = .feed
|
||
}
|
||
updateShowIcons() // Automatic depends on these articles’ author avatars, even when showFeedNames didn’t change
|
||
|
||
articleRowMap = [String: [Int]]()
|
||
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 {
|
||
updateShowIcons()
|
||
updateTableViewRowHeight()
|
||
reloadVisibleCells()
|
||
}
|
||
}
|
||
}
|
||
|
||
private(set) var showIcons = false
|
||
private var currentRowHeight: CGFloat = 0.0
|
||
private var largeThumbnailRowHeight: CGFloat = 0.0
|
||
private var articleIDsWithLargeThumbnailHeight = Set<String>() // Articles heightOfRow last gave largeThumbnailRowHeight
|
||
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 fontSize: FontSize = AppDefaults.timelineFontSize {
|
||
didSet {
|
||
if fontSize != oldValue {
|
||
fontSizeDidChange()
|
||
}
|
||
}
|
||
}
|
||
|
||
private struct ArticleIdentityKey: Equatable {
|
||
let accountID: String
|
||
let articleID: String
|
||
}
|
||
|
||
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.
|
||
userDefaultsDidChange()
|
||
thumbnailsDisplay = AppDefaults.timelineThumbnailsDisplay
|
||
updateCellAppearances()
|
||
|
||
updateRowHeights()
|
||
tableView.target = self
|
||
tableView.doubleAction = #selector(openArticleInBrowser(_:))
|
||
tableView.setDraggingSourceOperationMask(.copy, forLocal: false)
|
||
tableView.keyboardDelegate = keyboardDelegate
|
||
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(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(handleUserDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineThumbnailsDisplayDidChange(_:)), name: .timelineThumbnailsDisplayDidChange, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFeedIconsDisplayDidChange(_:)), name: .timelineFeedIconsDisplayDidChange, 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?) {
|
||
if let link = oneSelectedArticle?.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 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, 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
|
||
if thumbnailMode == .large {
|
||
noteHeightOfRowsThatGainedOrLostLargeThumbnail()
|
||
}
|
||
// Thumbnails that couldn’t download while offline or in Low Data Mode try again.
|
||
if ThumbnailDownloader.shared.networkAllowsDownloads {
|
||
reloadVisibleCells()
|
||
}
|
||
}
|
||
}
|
||
|
||
@objc nonisolated func handleUserDefaultsDidChange(_ notification: Notification) {
|
||
Task { @MainActor in
|
||
self.userDefaultsDidChange()
|
||
}
|
||
}
|
||
|
||
@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 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()
|
||
}
|
||
}
|
||
|
||
private func userDefaultsDidChange() {
|
||
fontSize = AppDefaults.timelineFontSize
|
||
updateGridStyle()
|
||
}
|
||
|
||
/// Separators between rows, never in column layout. `TimelineTableRowView` draws them.
|
||
private func updateGridStyle() {
|
||
let showsSeparators = layout == .standard && AppDefaults.timelineShowsSeparators
|
||
let gridStyleMask: NSTableView.GridLineStyle = showsSeparators ? .solidHorizontalGridLineMask : []
|
||
if tableView.gridStyleMask != gridStyleMask {
|
||
tableView.gridStyleMask = gridStyleMask
|
||
}
|
||
}
|
||
|
||
/// The one place the row height is set — it depends on the layout and the font size.
|
||
func updateTableViewRowHeight() {
|
||
tableView.rowHeight = layout == .column ? columnRowHeight() : currentRowHeight
|
||
}
|
||
|
||
// 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
|
||
|
||
private func calculateRowHeight(showThumbnail: Bool) -> 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: showThumbnail)
|
||
let height = TimelineCellLayout.height(for: Self.prototypeRowWidth, cellData: prototypeCellData, appearance: cellAppearance)
|
||
return height
|
||
}
|
||
|
||
private func updateRowHeights() {
|
||
currentRowHeight = calculateRowHeight(showThumbnail: false)
|
||
updateLargeThumbnailRowHeight()
|
||
updateTableViewRowHeight()
|
||
}
|
||
|
||
/// Depends on the cell appearance, which has the large thumbnail’s height only in large mode.
|
||
private func updateLargeThumbnailRowHeight() {
|
||
largeThumbnailRowHeight = calculateRowHeight(showThumbnail: true)
|
||
}
|
||
|
||
/// `oldArticles` are the same articles in the same order. An article with the same instance has the same images.
|
||
private func rowsThatGainedOrLostThumbnail(comparedWith oldArticles: ArticleArray) -> IndexSet {
|
||
var rows = IndexSet()
|
||
guard let thumbnailMode else {
|
||
return rows
|
||
}
|
||
for (row, (oldArticle, article)) in zip(oldArticles, articles).enumerated() where oldArticle !== article {
|
||
let hadThumbnail = ArticleThumbnailFinder.shared.thumbnailURL(for: oldArticle, mode: thumbnailMode) != nil
|
||
let hasThumbnail = ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) != nil
|
||
if hadThumbnail != hasThumbnail {
|
||
rows.insert(row)
|
||
}
|
||
}
|
||
return rows
|
||
}
|
||
|
||
/// For thumbnail choices that change with no failure notification, such as after a network change.
|
||
private func noteHeightOfRowsThatGainedOrLostLargeThumbnail() {
|
||
guard largeThumbnailRowHeight > 0.0 else {
|
||
return
|
||
}
|
||
var rows = IndexSet()
|
||
for (row, article) in articles.enumerated() {
|
||
let hasThumbnail = ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: .large) != nil
|
||
if hasThumbnail != articleIDsWithLargeThumbnailHeight.contains(article.articleID) {
|
||
rows.insert(row)
|
||
}
|
||
}
|
||
if !rows.isEmpty {
|
||
noteHeightOfRowsKeepingScrollPosition(rows)
|
||
}
|
||
}
|
||
|
||
/// 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 {
|
||
if let article = articles.articleAtRow(row) {
|
||
if thumbnailMode == .large, largeThumbnailRowHeight > 0.0, ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: .large) != nil {
|
||
articleIDsWithLargeThumbnailHeight.insert(article.articleID)
|
||
return largeThumbnailRowHeight
|
||
}
|
||
articleIDsWithLargeThumbnailHeight.remove(article.articleID)
|
||
}
|
||
// Keeping -[NSTableViewDelegate tableView:heightOfRow:] implemented fixes
|
||
// an issue that the bottom inset of NSTableView disappears on macOS Monterey.
|
||
return tableView.rowHeight
|
||
}
|
||
}
|
||
|
||
// 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? {
|
||
if layout == .column {
|
||
return columnCellView(for: tableColumn, row: row)
|
||
}
|
||
|
||
func configure(_ cell: TimelineTableCellView) {
|
||
cell.cellAppearance = showIcons ? cellAppearanceWithIcon : cellAppearance
|
||
if let article = articles.articleAtRow(row) {
|
||
configureTimelineCell(cell, article: article)
|
||
} 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) {
|
||
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(accountID: $0.accountID, articleID: $0.articleID) }
|
||
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, 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)
|
||
}
|
||
|
||
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() {
|
||
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 in large mode, and visible cells.
|
||
func thumbnailURLsDidChange(for articleIDs: Set<String>) {
|
||
guard !articleIDs.isEmpty else {
|
||
return
|
||
}
|
||
if thumbnailMode == .large {
|
||
noteHeightOfRowsKeepingScrollPosition(indexesForArticleIDs(articleIDs))
|
||
}
|
||
reloadVisibleCells(for: articleIDs)
|
||
}
|
||
|
||
func thumbnailsDisplayDidChange() {
|
||
updateCellAppearances()
|
||
updateLargeThumbnailRowHeight()
|
||
guard layout == .standard else {
|
||
return
|
||
}
|
||
performBlockAndRestoreSelection {
|
||
tableView.reloadData()
|
||
}
|
||
if tableView.selectedRow != -1 {
|
||
tableView.scrollRowToVisible(tableView.selectedRow)
|
||
}
|
||
}
|
||
|
||
// MARK: - Appearance Change
|
||
|
||
private func updateCellAppearances() {
|
||
cellAppearance = TimelineCellAppearance(showIcon: false, fontSize: fontSize, showsLargeThumbnails: thumbnailsDisplay == .large)
|
||
cellAppearanceWithIcon = TimelineCellAppearance(showIcon: true, fontSize: fontSize, showsLargeThumbnails: thumbnailsDisplay == .large)
|
||
}
|
||
|
||
private func fontSizeDidChange() {
|
||
updateCellAppearances()
|
||
updateRowHeights()
|
||
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
|
||
}
|
||
}
|