From 503a205115b7fb95d4808dfd94cfd04d8a19bbde Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 2 Jun 2026 21:55:59 -0700 Subject: [PATCH] Convert AccountStats over to xib. Add localization. --- Mac/AccountStats/AccountStatsFooterView.swift | 138 ------ Mac/AccountStats/AccountStatsLayout.swift | 31 -- .../AccountStatsViewController.swift | 334 -------------- Mac/AccountStats/AccountStatsViewModel.swift | 171 ++++---- .../AccountStatsWindowController.swift | 299 ++++++++++++- .../Base.lproj/AccountStatsWindow.xib | 409 ++++++++++++++++++ .../mul.lproj/AccountStatsWindow.xcstrings | 222 ++++++++++ 7 files changed, 994 insertions(+), 610 deletions(-) delete mode 100644 Mac/AccountStats/AccountStatsFooterView.swift delete mode 100644 Mac/AccountStats/AccountStatsLayout.swift delete mode 100644 Mac/AccountStats/AccountStatsViewController.swift create mode 100644 Mac/AccountStats/Base.lproj/AccountStatsWindow.xib create mode 100644 Mac/AccountStats/mul.lproj/AccountStatsWindow.xcstrings diff --git a/Mac/AccountStats/AccountStatsFooterView.swift b/Mac/AccountStats/AccountStatsFooterView.swift deleted file mode 100644 index 880296c0b..000000000 --- a/Mac/AccountStats/AccountStatsFooterView.swift +++ /dev/null @@ -1,138 +0,0 @@ -// -// AccountStatsFooterView.swift -// NetNewsWire -// -// Created by Brent Simmons on 4/7/26. -// - -import AppKit - -final class AccountStatsFooterView: NSView { - - private static let vacuumButtonTitle = NSLocalizedString("Vacuum Databases", comment: "Vacuum Databases button title") - - private let refreshButton: NSButton - private let vacuumButton: NSButton - private let vacuumSpinner = NSProgressIndicator() - private let helpButton: NSButton - private let explanationLabel: NSTextField - - init() { - refreshButton = NSButton() - refreshButton.bezelStyle = .rounded - refreshButton.title = NSLocalizedString("Refresh", comment: "Refresh button title") - refreshButton.translatesAutoresizingMaskIntoConstraints = false - refreshButton.target = nil - refreshButton.action = #selector(AccountStatsViewController.refresh(_:)) - - vacuumButton = NSButton() - vacuumButton.bezelStyle = .rounded - vacuumButton.title = Self.vacuumButtonTitle - vacuumButton.translatesAutoresizingMaskIntoConstraints = false - vacuumButton.target = nil - vacuumButton.action = #selector(AccountStatsViewController.vacuum(_:)) - - helpButton = NSButton() - helpButton.bezelStyle = .helpButton - helpButton.title = "" - helpButton.translatesAutoresizingMaskIntoConstraints = false - helpButton.setAccessibilityLabel(NSLocalizedString("Help — opens in browser", comment: "Help button accessibility label")) - helpButton.target = nil - helpButton.action = #selector(AccountStatsViewController.showHelp(_:)) - - explanationLabel = NSTextField(wrappingLabelWithString: NSLocalizedString("Vacuuming may make databases faster.", comment: "Vacuum explanation text")) - explanationLabel.translatesAutoresizingMaskIntoConstraints = false - explanationLabel.font = NSFont.systemFont(ofSize: AccountStatsLayout.bottomBarFontSize) - explanationLabel.textColor = .secondaryLabelColor - explanationLabel.alignment = .natural - - super.init(frame: .zero) - translatesAutoresizingMaskIntoConstraints = false - - vacuumSpinner.translatesAutoresizingMaskIntoConstraints = false - vacuumSpinner.style = .spinning - vacuumSpinner.controlSize = .small - vacuumSpinner.isHidden = true - vacuumSpinner.isIndeterminate = true - - // Spinner is centered inside the button so it visually replaces the title during vacuum. - vacuumButton.addSubview(vacuumSpinner) - - let divider = NSBox() - divider.boxType = .separator - divider.translatesAutoresizingMaskIntoConstraints = false - - let background = NSVisualEffectView() - background.translatesAutoresizingMaskIntoConstraints = false - background.blendingMode = .withinWindow - background.material = .titlebar - - // Empty view between the helper text and the Refresh button — absorbs slack - // so the helper text stays next to the Vacuum Databases button on the left - // and the Refresh button stays pinned to the trailing edge. - let spacer = NSView() - spacer.translatesAutoresizingMaskIntoConstraints = false - - let row = NSStackView(views: [vacuumButton, explanationLabel, spacer, refreshButton, helpButton]) - row.translatesAutoresizingMaskIntoConstraints = false - row.orientation = .horizontal - row.alignment = .centerY - row.spacing = 8 - row.distribution = .fill - - spacer.setContentHuggingPriority(.defaultLow, for: .horizontal) - spacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - - // Helper text sizes to its content so it sits next to the Vacuum button. - explanationLabel.setContentHuggingPriority(.required, for: .horizontal) - explanationLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) - refreshButton.setContentHuggingPriority(.required, for: .horizontal) - vacuumButton.setContentHuggingPriority(.required, for: .horizontal) - helpButton.setContentHuggingPriority(.required, for: .horizontal) - - addSubview(divider) - addSubview(background) - addSubview(row) - - let padding = AccountStatsLayout.horizontalPadding - let spacing = AccountStatsLayout.verticalSpacing - - NSLayoutConstraint.activate([ - divider.topAnchor.constraint(equalTo: topAnchor), - divider.leadingAnchor.constraint(equalTo: leadingAnchor), - divider.trailingAnchor.constraint(equalTo: trailingAnchor), - - background.topAnchor.constraint(equalTo: divider.bottomAnchor), - background.leadingAnchor.constraint(equalTo: leadingAnchor), - background.trailingAnchor.constraint(equalTo: trailingAnchor), - background.bottomAnchor.constraint(equalTo: bottomAnchor), - - row.topAnchor.constraint(equalTo: divider.bottomAnchor, constant: spacing), - row.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding), - row.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding), - row.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -spacing), - - vacuumButton.widthAnchor.constraint(equalToConstant: AccountStatsLayout.buttonWidth), - refreshButton.widthAnchor.constraint(equalTo: vacuumButton.widthAnchor), - - vacuumSpinner.centerXAnchor.constraint(equalTo: vacuumButton.centerXAnchor), - vacuumSpinner.centerYAnchor.constraint(equalTo: vacuumButton.centerYAnchor) - ]) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) is not supported") - } - - func updateVacuumState(_ isVacuuming: Bool) { - vacuumButton.isEnabled = !isVacuuming - vacuumButton.title = isVacuuming ? "" : Self.vacuumButtonTitle - vacuumSpinner.isHidden = !isVacuuming - if isVacuuming { - vacuumSpinner.startAnimation(nil) - } else { - vacuumSpinner.stopAnimation(nil) - } - } -} diff --git a/Mac/AccountStats/AccountStatsLayout.swift b/Mac/AccountStats/AccountStatsLayout.swift deleted file mode 100644 index b444da6ad..000000000 --- a/Mac/AccountStats/AccountStatsLayout.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// AccountStatsLayout.swift -// NetNewsWire -// -// Created by Brent Simmons on 4/7/26. -// - -import AppKit - -enum AccountStatsLayout { - - static let windowDefaultWidth: CGFloat = 800 - // Wide enough to fit all NSTableView columns at their initial widths plus inset-style - // chrome, intercell spacing, vertical scroller, and header padding. Clamps any prior - // narrow autosaved frame on next open. - static let windowMinWidth: CGFloat = 740 - static let windowMinHeight: CGFloat = 260 - static let windowDefaultHeight: CGFloat = 460 - static let horizontalPadding: CGFloat = 16 - static let verticalSpacing: CGFloat = 12 - static let buttonWidth: CGFloat = 160 - static let bottomBarFontSize: CGFloat = 16 // matches Activity Log / Error Log warning labels - - static func formattedNumber(_ value: Int) -> String { - NumberFormatter.localizedString(from: NSNumber(value: value), number: .decimal) - } - - static func formattedSize(_ bytes: Int) -> String { - Int64(bytes).formatted(.byteCount(style: .file)) - } -} diff --git a/Mac/AccountStats/AccountStatsViewController.swift b/Mac/AccountStats/AccountStatsViewController.swift deleted file mode 100644 index d6668cdb6..000000000 --- a/Mac/AccountStats/AccountStatsViewController.swift +++ /dev/null @@ -1,334 +0,0 @@ -// -// AccountStatsViewController.swift -// NetNewsWire -// -// Created by Brent Simmons on 4/7/26. -// - -import AppKit -import RSWeb - -final class AccountStatsViewController: NSViewController { - - private let model = AccountStatsViewModel() - private let scrollView = NSScrollView() - private let tableView = AccountStatsTableView() - private let footerView = AccountStatsFooterView() - - override func loadView() { - let containerView = NSView() - containerView.translatesAutoresizingMaskIntoConstraints = false - - configureScrollView() - configureTableView() - - containerView.addSubview(scrollView) - containerView.addSubview(footerView) - - NSLayoutConstraint.activate([ - scrollView.topAnchor.constraint(equalTo: containerView.topAnchor), - scrollView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), - scrollView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), - scrollView.bottomAnchor.constraint(equalTo: footerView.topAnchor), - - footerView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), - footerView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), - footerView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor) - ]) - - self.view = containerView - } - - override func viewDidLoad() { - super.viewDidLoad() - NotificationCenter.default.addObserver(self, selector: #selector(handleAccountStatsDidChange(_:)), name: .AccountStatsDidChange, object: model) - } - - override func viewDidAppear() { - super.viewDidAppear() - model.refresh() - } - - @objc func handleAccountStatsDidChange(_ notification: Notification) { - updateUI() - } - - @objc func refresh(_ sender: Any?) { - model.refresh() - } - - @objc func vacuum(_ sender: Any?) { - model.vacuum() - } - - @objc func showHelp(_ sender: Any?) { - if let url = URL(string: "https://netnewswire.com/help/account-stats.html") { - MacWebBrowser.openURL(url) - } - } -} - -// MARK: - NSTableViewDataSource - -extension AccountStatsViewController: NSTableViewDataSource { - - func numberOfRows(in tableView: NSTableView) -> Int { - model.accountStats.count + (showsTotalsRow ? 1 : 0) - } -} - -// MARK: - NSTableViewDelegate - -extension AccountStatsViewController: NSTableViewDelegate { - - func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { - guard let tableColumn else { - return nil - } - let identifier = tableColumn.identifier - let columnKind = columnKind(for: identifier) - - let cell: NSTableCellView - if let recycled = tableView.makeView(withIdentifier: identifier, owner: self) as? NSTableCellView { - cell = recycled - } else { - cell = Self.makeCell(identifier: identifier, alignment: columnKind.alignment) - } - let textField = cell.textField! - - if row == totalsRowIndex { - let font = columnKind.usesMonospacedDigits - ? NSFont.monospacedDigitSystemFont(ofSize: NSFont.systemFontSize, weight: .bold) - : NSFont.boldSystemFont(ofSize: NSFont.systemFontSize) - let paragraphStyle = NSMutableParagraphStyle() - paragraphStyle.alignment = columnKind.alignment - textField.font = font - textField.textColor = .labelColor - textField.attributedStringValue = NSAttributedString( - string: totalsText(for: columnKind), - attributes: [ - .font: font, - .foregroundColor: NSColor.labelColor, - .paragraphStyle: paragraphStyle - ] - ) - return cell - } - - guard row < model.accountStats.count else { - return nil - } - let stats = model.accountStats[row] - textField.stringValue = text(for: columnKind, stats: stats) - textField.textColor = stats.isActive ? .labelColor : .secondaryLabelColor - textField.font = columnKind.usesMonospacedDigits - ? NSFont.monospacedDigitSystemFont(ofSize: NSFont.systemFontSize, weight: .regular) - : NSFont.systemFont(ofSize: NSFont.systemFontSize) - return cell - } -} - -// MARK: - Private - -private extension AccountStatsViewController { - - enum ColumnKind: String, CaseIterable { - - case account, dbSize, feeds, folders, articles, statuses, unread, starred - - var identifier: NSUserInterfaceItemIdentifier { - NSUserInterfaceItemIdentifier(rawValue) - } - - var title: String { - switch self { - case .account: - return NSLocalizedString("Account", comment: "Account column header") - case .feeds: - return NSLocalizedString("Feeds", comment: "Feeds column header") - case .folders: - return NSLocalizedString("Folders", comment: "Folders column header") - case .articles: - return NSLocalizedString("Articles", comment: "Articles column header") - case .statuses: - return NSLocalizedString("Statuses", comment: "Statuses column header") - case .unread: - return NSLocalizedString("Unread", comment: "Unread column header") - case .starred: - return NSLocalizedString("Starred", comment: "Starred column header") - case .dbSize: - return NSLocalizedString("Databases", comment: "Databases size column header") - } - } - - var width: CGFloat { - switch self { - case .account: - return 130 - case .dbSize: - return 80 - case .articles, .statuses: - return 70 - case .feeds, .folders, .unread, .starred: - return 55 - } - } - - var alignment: NSTextAlignment { - switch self { - case .account: - return .left - default: - return .right - } - } - - var usesMonospacedDigits: Bool { - alignment == .right - } - - var flexes: Bool { - self == .account - } - } - - func configureScrollView() { - scrollView.translatesAutoresizingMaskIntoConstraints = false - scrollView.hasVerticalScroller = true - scrollView.hasHorizontalScroller = false - scrollView.drawsBackground = true - scrollView.documentView = tableView - } - - func configureTableView() { - tableView.translatesAutoresizingMaskIntoConstraints = false - tableView.usesAlternatingRowBackgroundColors = true - tableView.rowSizeStyle = .default - tableView.allowsColumnReordering = false - tableView.allowsColumnSelection = false - tableView.allowsEmptySelection = true - tableView.allowsMultipleSelection = false - tableView.style = .inset - tableView.delegate = self - tableView.dataSource = self - - for kind in ColumnKind.allCases { - let column = NSTableColumn(identifier: kind.identifier) - column.title = kind.title - column.width = kind.width - column.minWidth = kind.width - column.headerCell.alignment = kind.alignment - column.resizingMask = kind.flexes ? [.userResizingMask, .autoresizingMask] : [.userResizingMask] - tableView.addTableColumn(column) - } - } - - func updateUI() { - tableView.reloadData() - footerView.updateVacuumState(model.isVacuuming) - } - - var showsTotalsRow: Bool { - model.accountStats.count > 1 - } - - var totalsRowIndex: Int? { - showsTotalsRow ? model.accountStats.count : nil - } - - func columnKind(for identifier: NSUserInterfaceItemIdentifier) -> ColumnKind { - ColumnKind(rawValue: identifier.rawValue) ?? .account - } - - func totalsText(for kind: ColumnKind) -> String { - switch kind { - case .account: - return NSLocalizedString("Totals", comment: "Totals row label") - case .feeds: - return AccountStatsLayout.formattedNumber(model.totalFeedCount) - case .folders: - return AccountStatsLayout.formattedNumber(model.totalFolderCount) - case .articles: - return AccountStatsLayout.formattedNumber(model.totalArticleCount) - case .statuses: - return AccountStatsLayout.formattedNumber(model.totalStatusesCount) - case .unread: - return AccountStatsLayout.formattedNumber(model.totalUnreadCount) - case .starred: - return AccountStatsLayout.formattedNumber(model.totalStarredCount) - case .dbSize: - return AccountStatsLayout.formattedSize(model.totalDatabaseSizeBytes) - } - } - - func text(for kind: ColumnKind, stats: AccountStatsData) -> String { - switch kind { - case .account: - if stats.name == stats.typeName { - return stats.name - } - return "\(stats.name) (\(stats.typeName))" - case .feeds: - return AccountStatsLayout.formattedNumber(stats.feedCount) - case .folders: - return AccountStatsLayout.formattedNumber(stats.folderCount) - case .articles: - return stats.totalArticleCount.map { AccountStatsLayout.formattedNumber($0) } ?? "—" - case .statuses: - return stats.statusesCount.map { AccountStatsLayout.formattedNumber($0) } ?? "—" - case .unread: - return stats.unreadCount.map { AccountStatsLayout.formattedNumber($0) } ?? "—" - case .starred: - return stats.starredCount.map { AccountStatsLayout.formattedNumber($0) } ?? "—" - case .dbSize: - return AccountStatsLayout.formattedSize(stats.databaseSizeBytes) - } - } - - static func makeCell(identifier: NSUserInterfaceItemIdentifier, alignment: NSTextAlignment) -> NSTableCellView { - let cell = NSTableCellView() - cell.identifier = identifier - - let textField = NSTextField(labelWithString: "") - textField.translatesAutoresizingMaskIntoConstraints = false - textField.alignment = alignment - textField.lineBreakMode = .byTruncatingTail - cell.addSubview(textField) - cell.textField = textField - - NSLayoutConstraint.activate([ - textField.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 2), - textField.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -2), - textField.centerYAnchor.constraint(equalTo: cell.centerYAnchor) - ]) - - return cell - } -} - -// MARK: - AccountStatsTableView - -/// NSTableView that doesn't extend its alternating-row stripes below the last row. -final class AccountStatsTableView: NSTableView { - - override func drawBackground(inClipRect clipRect: NSRect) { - super.drawBackground(inClipRect: clipRect) - - guard numberOfRows > 0 else { - return - } - let belowLastRowY = rect(ofRow: numberOfRows - 1).maxY - guard belowLastRowY < clipRect.maxY else { - return - } - - let coverRect = NSRect( - x: clipRect.minX, - y: belowLastRowY, - width: clipRect.width, - height: clipRect.maxY - belowLastRowY - ) - (backgroundColor).setFill() - coverRect.fill() - } -} diff --git a/Mac/AccountStats/AccountStatsViewModel.swift b/Mac/AccountStats/AccountStatsViewModel.swift index f0ba2b7d3..b90981e26 100644 --- a/Mac/AccountStats/AccountStatsViewModel.swift +++ b/Mac/AccountStats/AccountStatsViewModel.swift @@ -9,11 +9,7 @@ import Foundation import Account import ArticlesDatabase -extension Notification.Name { - static let AccountStatsDidChange = Notification.Name("AccountStatsDidChange") -} - -struct AccountStatsData { +struct AccountStatsRowData { let accountID: String let name: String @@ -30,87 +26,86 @@ struct AccountStatsData { @MainActor final class AccountStatsViewModel { - var accountStats = [AccountStatsData]() - var isVacuuming = false + var accountStats = [String: AccountStatsRowData]() + private(set) var sortedAccountStats = [AccountStatsRowData]() + var sortDescriptor: NSSortDescriptor? - private var refreshGeneration = 0 - private var pendingAccountIDs = Set() - - // Async-derived totals stay stable through a refresh — they only update once every account has reported. private var cachedTotalArticleCount = 0 private var cachedTotalUnreadCount = 0 private var cachedTotalStarredCount = 0 private var cachedTotalStatusesCount = 0 - init() { - NotificationCenter.default.addObserver(self, selector: #selector(handleUserDidAddAccount(_:)), name: .UserDidAddAccount, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(handleUserDidDeleteAccount(_:)), name: .UserDidDeleteAccount, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(handleAccountStateDidChange(_:)), name: .AccountStateDidChange, object: nil) - } - - @objc func handleUserDidAddAccount(_ notification: Notification) { - refresh() - } - - @objc func handleUserDidDeleteAccount(_ notification: Notification) { - refresh() - } - - @objc func handleAccountStateDidChange(_ notification: Notification) { - refresh() - } - - func refresh() { - refreshGeneration += 1 - let generation = refreshGeneration - + func refresh() async { let accounts = AccountManager.shared.sortedAccounts - let previousByID = Dictionary(uniqueKeysWithValues: accountStats.map { ($0.accountID, $0) }) + let previous = accountStats - // Preserve previous async-loaded counts while the new fetches are in flight — cells stay - // at their old values instead of flickering to "—". - accountStats = accounts.map { account in - let previous = previousByID[account.accountID] - return AccountStatsData( + // Preserve previous async-loaded counts so cells keep their values until the new fetches return. + var newStats = [String: AccountStatsRowData]() + for account in accounts { + let previousData = previous[account.accountID] + newStats[account.accountID] = AccountStatsRowData( accountID: account.accountID, name: account.nameForDisplay, typeName: account.type.displayName, isActive: account.isActive, feedCount: account.flattenedFeeds().count, folderCount: account.folders?.count ?? 0, - totalArticleCount: previous?.totalArticleCount, - statusesCount: previous?.statusesCount, - unreadCount: previous?.unreadCount, - starredCount: previous?.starredCount, + totalArticleCount: previousData?.totalArticleCount, + statusesCount: previousData?.statusesCount, + unreadCount: previousData?.unreadCount, + starredCount: previousData?.starredCount, databaseSizeBytes: databaseSize(for: account) ) } - - pendingAccountIDs = Set(accounts.map { $0.accountID }) - NotificationCenter.default.post(name: .AccountStatsDidChange, object: self) + accountStats = newStats for account in accounts { - loadCounts(for: account, generation: generation) + guard let counts = try? await account.fetchArticleCountsAsync(), var stats = accountStats[account.accountID] else { + continue + } + stats.totalArticleCount = counts.totalCount + stats.unreadCount = counts.unreadCount + stats.starredCount = counts.starredCount + stats.statusesCount = counts.statusesCount + accountStats[account.accountID] = stats } + + recomputeCachedTotals() + applySort() } - func vacuum() { - isVacuuming = true - NotificationCenter.default.post(name: .AccountStatsDidChange, object: self) - - Task { - await appDelegate.vacuumAllDatabases() - isVacuuming = false - refresh() + func applySort() { + let unsorted = Array(accountStats.values) + let ascending = sortDescriptor?.ascending ?? true + let key = sortDescriptor?.key ?? "account" + switch key { + case "account": + sortedAccountStats = unsorted.sorted { Self.compareStrings($0.name, $1.name, ascending: ascending) } + case "dbSize": + sortedAccountStats = unsorted.sorted { Self.compareInts($0.databaseSizeBytes, $1.databaseSizeBytes, ascending: ascending) } + case "feeds": + sortedAccountStats = unsorted.sorted { Self.compareInts($0.feedCount, $1.feedCount, ascending: ascending) } + case "folders": + sortedAccountStats = unsorted.sorted { Self.compareInts($0.folderCount, $1.folderCount, ascending: ascending) } + case "articles": + sortedAccountStats = unsorted.sorted { Self.compareOptionalInts($0.totalArticleCount, $1.totalArticleCount, ascending: ascending) } + case "statuses": + sortedAccountStats = unsorted.sorted { Self.compareOptionalInts($0.statusesCount, $1.statusesCount, ascending: ascending) } + case "unread": + sortedAccountStats = unsorted.sorted { Self.compareOptionalInts($0.unreadCount, $1.unreadCount, ascending: ascending) } + case "starred": + sortedAccountStats = unsorted.sorted { Self.compareOptionalInts($0.starredCount, $1.starredCount, ascending: ascending) } + default: + sortedAccountStats = unsorted } } var totalFeedCount: Int { - accountStats.reduce(0) { $0 + $1.feedCount } + accountStats.values.reduce(0) { $0 + $1.feedCount } } var totalFolderCount: Int { - accountStats.reduce(0) { $0 + $1.folderCount } + accountStats.values.reduce(0) { $0 + $1.folderCount } } var totalArticleCount: Int { @@ -130,58 +125,48 @@ struct AccountStatsData { } var totalDatabaseSizeBytes: Int { - accountStats.reduce(0) { $0 + $1.databaseSizeBytes } + accountStats.values.reduce(0) { $0 + $1.databaseSizeBytes } } } private extension AccountStatsViewModel { - func loadCounts(for account: Account, generation: Int) { - let accountID = account.accountID - Task { @MainActor in - let counts = try? await account.fetchArticleCountsAsync() - guard generation == refreshGeneration else { - return - } - guard let counts else { - // Fetch failed (database suspended, etc.) — leave previous values in place. - pendingAccountIDs.remove(accountID) - if pendingAccountIDs.isEmpty { - recomputeCachedTotals() - NotificationCenter.default.post(name: .AccountStatsDidChange, object: self) - } - return - } - guard let index = accountStats.firstIndex(where: { $0.accountID == accountID }) else { - return - } - accountStats[index].totalArticleCount = counts.totalCount - accountStats[index].unreadCount = counts.unreadCount - accountStats[index].starredCount = counts.starredCount - accountStats[index].statusesCount = counts.statusesCount + static func compareStrings(_ lhs: String, _ rhs: String, ascending: Bool) -> Bool { + let result = lhs.localizedCaseInsensitiveCompare(rhs) + return ascending ? result == .orderedAscending : result == .orderedDescending + } - pendingAccountIDs.remove(accountID) - if pendingAccountIDs.isEmpty { - recomputeCachedTotals() - } - NotificationCenter.default.post(name: .AccountStatsDidChange, object: self) + static func compareInts(_ lhs: Int, _ rhs: Int, ascending: Bool) -> Bool { + ascending ? lhs < rhs : lhs > rhs + } + + static func compareOptionalInts(_ lhs: Int?, _ rhs: Int?, ascending: Bool) -> Bool { + switch (lhs, rhs) { + case (nil, nil): + return false + case (nil, _): + return ascending + case (_, nil): + return !ascending + case let (l?, r?): + return ascending ? l < r : l > r } } func recomputeCachedTotals() { - cachedTotalArticleCount = accountStats.reduce(0) { $0 + ($1.totalArticleCount ?? 0) } - cachedTotalUnreadCount = accountStats.reduce(0) { $0 + ($1.unreadCount ?? 0) } - cachedTotalStarredCount = accountStats.reduce(0) { $0 + ($1.starredCount ?? 0) } - cachedTotalStatusesCount = accountStats.reduce(0) { $0 + ($1.statusesCount ?? 0) } + cachedTotalArticleCount = accountStats.values.reduce(0) { $0 + ($1.totalArticleCount ?? 0) } + cachedTotalUnreadCount = accountStats.values.reduce(0) { $0 + ($1.unreadCount ?? 0) } + cachedTotalStarredCount = accountStats.values.reduce(0) { $0 + ($1.starredCount ?? 0) } + cachedTotalStatusesCount = accountStats.values.reduce(0) { $0 + ($1.statusesCount ?? 0) } } func databaseSize(for account: Account) -> Int { let dataFolder = account.dataFolder as NSString - let baseNames = ["DB.sqlite3", "FeedSettings.db", "Sync.sqlite3"] + let databaseNames = ["DB.sqlite3", "FeedSettings.db", "Sync.sqlite3"] var totalSize = 0 - for baseName in baseNames { - let path = dataFolder.appendingPathComponent(baseName) + for databaseName in databaseNames { + let path = dataFolder.appendingPathComponent(databaseName) if let attributes = try? FileManager.default.attributesOfItem(atPath: path), let size = attributes[FileAttributeKey.size] as? Int { totalSize += size diff --git a/Mac/AccountStats/AccountStatsWindowController.swift b/Mac/AccountStats/AccountStatsWindowController.swift index 98283c73b..fb605ffc3 100644 --- a/Mac/AccountStats/AccountStatsWindowController.swift +++ b/Mac/AccountStats/AccountStatsWindowController.swift @@ -6,6 +6,9 @@ // import AppKit +import Account +import RSCore +import RSWeb final class AccountStatsWindowController: NSWindowController { @@ -20,23 +23,28 @@ final class AccountStatsWindowController: NSWindowController { } } + @IBOutlet private var tableView: UtilityTableView? + @IBOutlet private var vacuumButton: NSButton? + @IBOutlet private var vacuumSpinner: NSProgressIndicator? + + private let model = AccountStatsViewModel() private var hasBeenShown = false - - init() { - let size = NSSize(width: AccountStatsLayout.windowDefaultWidth, height: AccountStatsLayout.windowDefaultHeight) - let window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: true) - window.title = NSLocalizedString("Account Stats", comment: "Account Stats window title") - window.isReleasedWhenClosed = false - window.minSize = NSSize(width: AccountStatsLayout.windowMinWidth, height: AccountStatsLayout.windowMinHeight) - window.contentViewController = AccountStatsViewController() - window.setFrameAutosaveName("AccountStatsWindow") - - super.init(window: window) + private var hasFittedColumns = false + private var isVacuuming = false { + didSet { + updateVacuumUI() + } } - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) is not supported") + convenience init() { + self.init(windowNibName: "AccountStatsWindow") + } + + override func windowDidLoad() { + super.windowDidLoad() + NotificationCenter.default.addObserver(self, selector: #selector(handleUserDidAddAccount(_:)), name: .UserDidAddAccount, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleUserDidDeleteAccount(_:)), name: .UserDidDeleteAccount, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleAccountStateDidChange(_:)), name: .AccountStateDidChange, object: nil) } override func showWindow(_ sender: Any?) { @@ -44,10 +52,273 @@ final class AccountStatsWindowController: NSWindowController { hasBeenShown = true window?.center() } + if !hasFittedColumns { + fitColumnsToLocalizedHeaders() + hasFittedColumns = true + } super.showWindow(sender) + refreshModel() } func saveState() { Self.shouldOpenAtStartup = window?.isVisible ?? false } + + @objc func handleUserDidAddAccount(_ notification: Notification) { + refreshModel() + } + + @objc func handleUserDidDeleteAccount(_ notification: Notification) { + refreshModel() + } + + @objc func handleAccountStateDidChange(_ notification: Notification) { + refreshModel() + } + + @objc func refresh(_ sender: Any?) { + refreshModel() + } + + @objc func vacuum(_ sender: Any?) { + guard !isVacuuming else { + return + } + isVacuuming = true + Task { + await appDelegate.vacuumAllDatabases() + isVacuuming = false + refreshModel() + } + } + + @objc func showHelp(_ sender: Any?) { + if let url = URL(string: "https://netnewswire.com/help/account-stats.html") { + MacWebBrowser.openURL(url) + } + } +} + +// MARK: - NSTableViewDataSource + +extension AccountStatsWindowController: NSTableViewDataSource { + + func numberOfRows(in tableView: NSTableView) -> Int { + model.sortedAccountStats.count + (showsTotalsRow ? 1 : 0) + } + + func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { + model.sortDescriptor = tableView.sortDescriptors.first + model.applySort() + reloadData() + } +} + +// MARK: - NSTableViewDelegate + +extension AccountStatsWindowController: NSTableViewDelegate { + + func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { + guard let tableColumn else { + return nil + } + let identifier = tableColumn.identifier + let columnKind = columnKind(for: identifier) + + guard let cell = tableView.makeView(withIdentifier: identifier, owner: self) as? NSTableCellView else { + return nil + } + guard let textField = cell.textField else { + return cell + } + + let pointSize = textField.font?.pointSize ?? NSFont.systemFontSize + + if row == totalsRowIndex { + let font = columnKind.usesMonospacedDigits + ? NSFont.monospacedDigitSystemFont(ofSize: pointSize, weight: .bold) + : NSFont.boldSystemFont(ofSize: pointSize) + let paragraph = NSMutableParagraphStyle() + paragraph.alignment = columnKind.alignment + textField.alignment = columnKind.alignment + textField.attributedStringValue = NSAttributedString( + string: totalsText(for: columnKind), + attributes: [ + .font: font, + .foregroundColor: NSColor.labelColor, + .paragraphStyle: paragraph + ] + ) + return cell + } + + guard row < model.sortedAccountStats.count else { + return nil + } + let accountData = model.sortedAccountStats[row] + textField.stringValue = text(for: columnKind, stats: accountData) + textField.textColor = accountData.isActive ? .labelColor : .secondaryLabelColor + textField.alignment = columnKind.alignment + textField.font = columnKind.usesMonospacedDigits + ? NSFont.monospacedDigitSystemFont(ofSize: pointSize, weight: .regular) + : NSFont.systemFont(ofSize: pointSize) + return cell + } +} + +// MARK: - Private + +private extension AccountStatsWindowController { + + enum ColumnKind: String { + + case account, dbSize, feeds, folders, articles, statuses, unread, starred + + var alignment: NSTextAlignment { + switch self { + case .account: + return .left + default: + return .right + } + } + + var usesMonospacedDigits: Bool { + self != .account + } + } + + func refreshModel() { + Task { + await model.refresh() + reloadData() + } + } + + func reloadData() { + tableView?.reloadData() + updateUI() + } + + func updateUI() { + updateVacuumUI() + } + + func updateVacuumUI() { + vacuumButton?.isEnabled = !isVacuuming + vacuumSpinner?.isHidden = !isVacuuming + if isVacuuming { + vacuumSpinner?.startAnimation(nil) + } else { + vacuumSpinner?.stopAnimation(nil) + } + } + + + func fitColumnsToLocalizedHeaders() { + guard let tableView else { + return + } + // Cell-side padding (~6pt each side) + sort-indicator triangle (~12pt) + breathing. + let headerPadding: CGFloat = 28 + // Extra width above the minimum so the user has room to drag a column narrower. + let shrinkSlack: CGFloat = 28 + let headerFont = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize) + var totalColumnWidth: CGFloat = 0 + for column in tableView.tableColumns { + let title = column.headerCell.stringValue + let titleWidth = (title as NSString).size(withAttributes: [.font: headerFont]).width + let required = ceil(titleWidth) + headerPadding + if required > column.minWidth { + column.minWidth = required + } + if required > column.width { + column.width = required + shrinkSlack + } + totalColumnWidth += column.width + } + + // The XIB's contentMinSize was sized for English. Widen it if the localized + // columns plus chrome can't fit, otherwise the table view squeezes columns + // below their minWidth and they clip. + guard let window else { + return + } + let intercellSpacing = tableView.intercellSpacing.width * CGFloat(tableView.tableColumns.count - 1) + let chrome: CGFloat = 24 // vertical scroller + a little slack + let requiredContentWidth = ceil(totalColumnWidth + intercellSpacing + chrome) + if requiredContentWidth > window.contentMinSize.width { + window.contentMinSize = NSSize(width: requiredContentWidth, height: window.contentMinSize.height) + } + if requiredContentWidth > window.frame.size.width { + var frame = window.frame + frame.size.width = requiredContentWidth + window.setFrame(frame, display: true) + } + } + + var showsTotalsRow: Bool { + model.sortedAccountStats.count > 1 + } + + var totalsRowIndex: Int? { + showsTotalsRow ? model.sortedAccountStats.count : nil + } + + func columnKind(for identifier: NSUserInterfaceItemIdentifier) -> ColumnKind { + ColumnKind(rawValue: identifier.rawValue) ?? .account + } + + func totalsText(for kind: ColumnKind) -> String { + switch kind { + case .account: + return NSLocalizedString("Totals", comment: "Totals row label") + case .feeds: + return Self.formattedNumber(model.totalFeedCount) + case .folders: + return Self.formattedNumber(model.totalFolderCount) + case .articles: + return Self.formattedNumber(model.totalArticleCount) + case .statuses: + return Self.formattedNumber(model.totalStatusesCount) + case .unread: + return Self.formattedNumber(model.totalUnreadCount) + case .starred: + return Self.formattedNumber(model.totalStarredCount) + case .dbSize: + return Self.formattedSize(model.totalDatabaseSizeBytes) + } + } + + func text(for kind: ColumnKind, stats: AccountStatsRowData) -> String { + switch kind { + case .account: + if stats.name == stats.typeName { + return stats.name + } + return "\(stats.name) (\(stats.typeName))" + case .feeds: + return Self.formattedNumber(stats.feedCount) + case .folders: + return Self.formattedNumber(stats.folderCount) + case .articles: + return stats.totalArticleCount.map { Self.formattedNumber($0) } ?? "—" + case .statuses: + return stats.statusesCount.map { Self.formattedNumber($0) } ?? "—" + case .unread: + return stats.unreadCount.map { Self.formattedNumber($0) } ?? "—" + case .starred: + return stats.starredCount.map { Self.formattedNumber($0) } ?? "—" + case .dbSize: + return Self.formattedSize(stats.databaseSizeBytes) + } + } + + static func formattedNumber(_ value: Int) -> String { + NumberFormatter.localizedString(from: NSNumber(value: value), number: .decimal) + } + + static func formattedSize(_ bytes: Int) -> String { + Int64(bytes).formatted(.byteCount(style: .file)) + } } diff --git a/Mac/AccountStats/Base.lproj/AccountStatsWindow.xib b/Mac/AccountStats/Base.lproj/AccountStatsWindow.xib new file mode 100644 index 000000000..7e149973f --- /dev/null +++ b/Mac/AccountStats/Base.lproj/AccountStatsWindow.xib @@ -0,0 +1,409 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Mac/AccountStats/mul.lproj/AccountStatsWindow.xcstrings b/Mac/AccountStats/mul.lproj/AccountStatsWindow.xcstrings new file mode 100644 index 000000000..09198187c --- /dev/null +++ b/Mac/AccountStats/mul.lproj/AccountStatsWindow.xcstrings @@ -0,0 +1,222 @@ +{ + "sourceLanguage" : "en", + "strings" : { + "0cO-dq-wRh.headerCell.title" : { + "comment" : "Class = \"NSTableColumn\"; headerCell.title = \"Starred\"; ObjectID = \"0cO-dq-wRh\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Starred" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Destacados" + } + } + } + }, + "1Nz-s2-tlh.title" : { + "comment" : "Class = \"NSButtonCell\"; title = \"Refresh\"; ObjectID = \"1Nz-s2-tlh\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Refresh" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Actualizar" + } + } + } + }, + "5F9-ka-Ic8.headerCell.title" : { + "comment" : "Class = \"NSTableColumn\"; headerCell.title = \"Feeds\"; ObjectID = \"5F9-ka-Ic8\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Feeds" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Fuentes" + } + } + } + }, + "A8s-1h-rFK.headerCell.title" : { + "comment" : "Class = \"NSTableColumn\"; headerCell.title = \"Articles\"; ObjectID = \"A8s-1h-rFK\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Articles" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Artículos" + } + } + } + }, + "el9-XU-UyQ.headerCell.title" : { + "comment" : "Class = \"NSTableColumn\"; headerCell.title = \"Databases\"; ObjectID = \"el9-XU-UyQ\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Databases" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bases de datos" + } + } + } + }, + "JJX-19-V6q.headerCell.title" : { + "comment" : "Class = \"NSTableColumn\"; headerCell.title = \"Statuses\"; ObjectID = \"JJX-19-V6q\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Statuses" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Estados" + } + } + } + }, + "JLZ-2v-hkU.headerCell.title" : { + "comment" : "Class = \"NSTableColumn\"; headerCell.title = \"Account\"; ObjectID = \"JLZ-2v-hkU\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Account" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cuenta" + } + } + } + }, + "Jvt-nt-V8z.headerCell.title" : { + "comment" : "Class = \"NSTableColumn\"; headerCell.title = \"Folders\"; ObjectID = \"Jvt-nt-V8z\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Folders" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Carpetas" + } + } + } + }, + "KiW-Nc-bVK.title" : { + "comment" : "Class = \"NSButtonCell\"; title = \"Vacuum Databases\"; ObjectID = \"KiW-Nc-bVK\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Vacuum Databases" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Compactar bases de datos" + } + } + } + }, + "QvC-M9-y7g.title" : { + "comment" : "Class = \"NSWindow\"; title = \"Account Stats\"; ObjectID = \"QvC-M9-y7g\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Account Stats" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Estadísticas de cuentas" + } + } + } + }, + "RQ5-kB-Icw.headerCell.title" : { + "comment" : "Class = \"NSTableColumn\"; headerCell.title = \"Unread\"; ObjectID = \"RQ5-kB-Icw\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Unread" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "No leídos" + } + } + } + }, + "xwg-oc-6B1.title" : { + "comment" : "Class = \"NSTextFieldCell\"; title = \"Vacuuming may make databases faster.\"; ObjectID = \"xwg-oc-6B1\";", + "extractionState" : "extracted_with_value", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Vacuuming may make databases faster." + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Compactar puede acelerar las bases de datos." + } + } + } + } + }, + "version" : "1.2" +} \ No newline at end of file