Files
NetNewsWire/Mac/MainWindow/MainWindowController.swift
T

1902 lines
65 KiB
Swift
Raw Normal View History

2017-05-27 10:43:27 -07:00
//
// MainWindowController.swift
2018-08-28 22:18:24 -07:00
// NetNewsWire
2017-05-27 10:43:27 -07:00
//
// Created by Brent Simmons on 8/1/15.
// Copyright © 2015 Ranchero Software, LLC. All rights reserved.
//
import AppKit
import os
2019-10-03 11:39:48 -05:00
import UserNotifications
import Articles
import Account
import RSCore
2017-05-27 10:43:27 -07:00
enum TimelineSourceMode {
case regular, search
}
2026-01-01 18:07:54 -08:00
final class MainWindowController: NSWindowController, NSUserInterfaceValidations {
static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "MainWindowController")
private var activityManager = ActivityManager()
2019-10-03 15:49:27 -05:00
2019-09-19 17:25:36 -05:00
private var isShowingExtractedArticle = false
2026-01-01 15:59:20 -08:00
private var articleExtractor: ArticleExtractor?
private var sharingServicePickerDelegate: SharingServicePickerDelegate?
2017-05-27 10:43:27 -07:00
private let windowAutosaveName = NSWindow.FrameAutosaveName("MainWindow")
private static let mainWindowWidthsStateKey = "mainWindowWidthsStateKey"
2019-02-17 18:46:28 -08:00
private var currentFeedOrFolder: AnyObject? {
// Nil for none or multiple selection.
guard let selectedObjects = selectedObjectsInSidebar(), selectedObjects.count == 1 else {
return nil
2017-10-18 21:53:45 -07:00
}
2019-02-17 18:46:28 -08:00
return selectedObjects.first
2017-10-18 21:53:45 -07:00
}
2025-11-05 11:22:10 -08:00
private var shareToolbarItem: NSToolbarItem? {
return window?.toolbar?.existingItem(withIdentifier: .share)
}
2026-09-19 10:44:51 -07:00
private static let detailViewMinimumWidth = 384
private static let detailViewMinimumHeight: CGFloat = 200
private static let timelineMinimumHeight: CGFloat = 120
private static let sidebarMinimumWidth: CGFloat = 96
// Used for the timeline when column layout has no saved height.
private static let defaultColumnLayoutTimelineHeightFraction: CGFloat = 0.4
2026-09-17 21:57:13 -07:00
private static let sidebarHoldingPriority: Float = 260
private static let timelineHoldingPriority: Float = 255
private static let toolbarIdentifier = "MainWindowToolbar"
2026-09-17 21:57:13 -07:00
private var splitViewController: NSSplitViewController?
2026-09-19 10:44:51 -07:00
// Column layout only: the vertical split holding the timeline above the article view.
private var contentSplitViewController: NSSplitViewController?
private var timelineLayout = AppDefaults.timelineLayout
2026-09-19 10:44:51 -07:00
// Geometry for the layout that isn’t showing, so a round trip through the other layout keeps it.
private var rememberedStandardLayoutWidths = [Int]()
private var rememberedColumnLayoutTimelineHeight = 0
2019-02-18 13:10:16 -08:00
private var sidebarViewController: SidebarViewController?
private var timelineContainerViewController: TimelineContainerViewController?
private var detailViewController: DetailViewController?
2026-01-01 15:59:20 -08:00
private var currentSearchField: NSSearchField?
private var searchString: String?
private var lastSentSearchString: String?
private var timelineSourceMode: TimelineSourceMode = .regular {
didSet {
timelineContainerViewController?.showTimeline(for: timelineSourceMode)
detailViewController?.showDetail(for: timelineSourceMode)
updateStatusBarLink()
}
}
2026-01-01 15:59:20 -08:00
private var searchSmartFeed: SmartFeed?
private var restoreArticleWindowScrollY: CGFloat?
// Holds the split view controller and the status bar.
private let mainWindowContentViewController = MainWindowContentViewController()
private var mouseoverLink: String? {
didSet {
updateStatusBarLink()
}
}
// MARK: - NSWindowController
2026-09-17 21:57:13 -07:00
convenience init() {
self.init(windowNibName: "MainWindow")
}
override func windowDidLoad() {
super.windowDidLoad()
if let window = window {
let point = NSPoint(x: 128, y: 64)
2020-08-20 20:00:31 -05:00
let size = NSSize(width: 1345, height: 900)
let minSize = NSSize(width: 600, height: 600)
window.setPointAndSizeAdjustingForScreen(point: point, size: size, minimumSize: minSize)
}
2026-09-19 10:44:51 -07:00
// The three panes live for the window’s life. Switching layout rebuilds only the split views around them.
let sidebarViewController = SidebarViewController()
sidebarViewController.delegate = self
sidebarViewController.view.translatesAutoresizingMaskIntoConstraints = false
sidebarViewController.view.widthAnchor.constraint(greaterThanOrEqualToConstant: Self.sidebarMinimumWidth).isActive = true
self.sidebarViewController = sidebarViewController
2019-02-17 19:38:17 -08:00
2026-09-19 10:44:51 -07:00
let timelineContainerViewController = TimelineContainerViewController()
timelineContainerViewController.delegate = self
self.timelineContainerViewController = timelineContainerViewController
let detailViewController = DetailViewController()
detailViewController.delegate = self
self.detailViewController = detailViewController
mainWindowContentViewController.statusBarView.delegate = self
updateStatusBarVisibility()
2019-02-17 19:38:17 -08:00
2026-09-19 10:44:51 -07:00
installSplitViewController(for: timelineLayout)
2019-02-17 22:00:04 -08:00
2026-09-19 10:44:51 -07:00
sharingServicePickerDelegate = SharingServicePickerDelegate(self.window)
2026-09-19 10:44:51 -07:00
NotificationCenter.default.addObserver(self, selector: #selector(handleUserDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshDidBegin, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshDidFinish, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .progressInfoDidChange, object: CombinedRefreshProgress.shared)
2017-10-18 21:53:45 -07:00
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleUnreadCountDisplaySettingDidChange(_:)), name: .unreadCountDisplaySettingDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil)
2025-11-05 11:22:10 -08:00
2021-09-08 19:58:40 -05:00
NotificationCenter.default.addObserver(self, selector: #selector(articleThemeNamesDidChangeNotification(_:)), name: .ArticleThemeNamesDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(currentArticleThemeDidChangeNotification(_:)), name: .CurrentArticleThemeDidChangeNotification, object: nil)
2025-11-05 11:22:10 -08:00
2017-10-18 21:53:45 -07:00
DispatchQueue.main.async {
self.updateWindowTitle()
2017-05-27 10:43:27 -07:00
}
2017-10-18 21:53:45 -07:00
}
2018-01-21 11:35:50 -08:00
// MARK: - API
2018-01-21 11:35:50 -08:00
func selectedObjectsInSidebar() -> [AnyObject]? {
return sidebarViewController?.selectedObjects
}
func selectedContainerInSidebar() -> Container? {
sidebarViewController?.selectedContainer
}
2026-06-01 08:39:09 -07:00
func selectFeedInSidebar(_ feed: Feed) {
sidebarViewController?.selectFeed(feed)
}
2019-10-03 11:39:48 -05:00
func handle(_ response: UNNotificationResponse) {
let userInfo = response.notification.request.content.userInfo
2026-01-01 18:07:54 -08:00
guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable: Any] else { return }
sidebarViewController?.deepLinkRevealAndSelect(for: articlePathUserInfo)
currentTimelineViewController?.goToDeepLink(for: articlePathUserInfo)
2019-10-03 11:39:48 -05:00
}
2019-10-03 15:49:27 -05:00
func handle(_ activity: NSUserActivity) {
guard let userInfo = activity.userInfo else { return }
2026-01-01 18:07:54 -08:00
guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable: Any] else { return }
sidebarViewController?.deepLinkRevealAndSelect(for: articlePathUserInfo)
currentTimelineViewController?.goToDeepLink(for: articlePathUserInfo)
2019-10-03 15:49:27 -05:00
}
func saveStateToUserDefaults() {
let state = savableState()
Self.logger.debug("MainWindowController: Saving state to UserDefaults: \(state)")
let data = try? NSKeyedArchiver.archivedData(withRootObject: state, requiringSecureCoding: true)
AppDefaults.secureWindowState = data
// Don't save the frame in full screen — it would replace the saved windowed frame with the screen's frame.
if let window, !window.styleMask.contains(.fullScreen) {
window.saveFrame(usingName: windowAutosaveName)
}
}
2025-11-05 11:22:10 -08:00
func restoreStateFromUserDefaults() {
if let data = AppDefaults.secureWindowState,
let state = try? NSKeyedUnarchiver.unarchivedObject(ofClass: MainWindowState.self, from: data) {
Self.logger.debug("MainWindowController: restoring state from UserDefaults: \(state)")
window?.setFrameUsingName(windowAutosaveName, force: true)
restoreState(from: state)
} else if let state = AppDefaults.legacyWindowState {
// Migrate from previous window state data. Delete data when finished.
window?.setFrameUsingName(windowAutosaveName, force: true)
restoreLegacyState(from: state)
AppDefaults.deleteLegacyWindowState()
}
}
// MARK: - Notifications
2026-09-19 10:44:51 -07:00
@objc nonisolated func handleUserDefaultsDidChange(_ note: Notification) {
Task { @MainActor in
self.userDefaultsDidChange()
}
}
private func userDefaultsDidChange() {
let layout = AppDefaults.timelineLayout
2026-09-19 10:44:51 -07:00
if layout != timelineLayout {
installSplitViewController(for: layout)
}
updateStatusBarVisibility()
}
2017-09-17 12:54:08 -07:00
@objc func refreshProgressDidChange(_ note: Notification) {
CoalescingQueue.standard.add(self, #selector(makeToolbarValidate))
2017-05-27 10:43:27 -07:00
}
2017-10-18 21:53:45 -07:00
@objc func unreadCountDidChange(_ note: Notification) {
CoalescingQueue.standard.add(self, #selector(coalescedUpdateWindowTitle))
}
@objc func handleUnreadCountDisplaySettingDidChange(_ notification: Notification) {
updateWindowTitle()
}
@objc func coalescedUpdateWindowTitle() {
updateWindowTitle()
}
2025-11-05 11:22:10 -08:00
@objc func displayNameDidChange(_ note: Notification) {
updateWindowTitleIfNecessary(note.object)
2017-10-18 21:53:45 -07:00
}
2021-09-08 19:58:40 -05:00
@objc func articleThemeNamesDidChangeNotification(_ note: Notification) {
updateArticleThemeMenu()
2021-09-08 19:58:40 -05:00
}
@objc func currentArticleThemeDidChangeNotification(_ note: Notification) {
updateArticleThemeMenu()
2021-09-08 19:58:40 -05:00
}
private func updateWindowTitleIfNecessary(_ noteObject: Any?) {
2025-11-05 11:22:10 -08:00
if let folder = currentFeedOrFolder as? Folder, let noteObject = noteObject as? Folder {
if folder == noteObject {
updateWindowTitle()
return
}
}
2025-11-05 11:22:10 -08:00
2025-11-02 14:51:46 -08:00
if let feed = currentFeedOrFolder as? Feed, let noteObject = noteObject as? Feed {
if feed == noteObject {
updateWindowTitle()
return
}
}
2025-11-05 11:22:10 -08:00
// If we don't recognize the changed object, we will test it for identity instead
2018-09-19 11:26:19 -05:00
// of equality. This works well for us if the window title is displaying a
// PsuedoFeed object.
if let currentObject = currentFeedOrFolder, let noteObject = noteObject {
if currentObject === noteObject as AnyObject {
updateWindowTitle()
}
}
2025-11-05 11:22:10 -08:00
}
// MARK: - Toolbar
2025-11-05 11:22:10 -08:00
@objc func makeToolbarValidate() {
2025-11-05 11:22:10 -08:00
2017-05-27 10:43:27 -07:00
window?.toolbar?.validateVisibleItems()
}
// MARK: - NSUserInterfaceValidations
2025-11-05 11:22:10 -08:00
2017-05-27 10:43:27 -07:00
public func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
2025-11-05 11:22:10 -08:00
if item.action == #selector(copyArticleURL(_:)) {
return canCopyArticleURL()
}
2025-11-05 11:22:10 -08:00
if item.action == #selector(copyExternalURL(_:)) {
return canCopyExternalURL()
}
2025-11-05 11:22:10 -08:00
2017-05-27 10:43:27 -07:00
if item.action == #selector(openArticleInBrowser(_:)) {
if let item = item as? NSMenuItem, item.keyEquivalentModifierMask.contains(.shift) {
item.title = Browser.titleForOpenInBrowserInverted
}
2020-05-20 19:54:25 -05:00
2017-05-27 10:43:27 -07:00
return currentLink != nil
}
2025-11-05 11:22:10 -08:00
2017-05-27 10:43:27 -07:00
if item.action == #selector(nextUnread(_:)) {
return canGoToNextUnread(wrappingToTop: true)
2017-05-27 10:43:27 -07:00
}
2025-11-05 11:22:10 -08:00
2017-05-27 10:43:27 -07:00
if item.action == #selector(markAllAsRead(_:)) {
return canMarkAllAsRead()
}
2017-11-05 21:27:34 -08:00
if item.action == #selector(toggleRead(_:)) {
return validateToggleRead(item)
2017-11-05 21:27:34 -08:00
}
if item.action == #selector(toggleStarred(_:)) {
return validateToggleStarred(item)
}
if item.action == #selector(markAboveArticlesAsRead(_:)) {
return canMarkAboveArticlesAsRead()
}
if item.action == #selector(markBelowArticlesAsRead(_:)) {
return canMarkBelowArticlesAsRead()
}
2019-09-18 18:15:55 -05:00
if item.action == #selector(toggleArticleExtractor(_:)) {
return validateToggleArticleExtractor(item)
}
2025-11-05 11:22:10 -08:00
if item.action == #selector(toolbarShowShareMenu(_:)) {
return canShowShareMenu()
}
if item.action == #selector(moveFocusToSearchField(_:)) {
return currentSearchField != nil
}
2020-03-15 18:02:55 -05:00
if item.action == #selector(cleanUp(_:)) {
return validateCleanUp(item)
}
if item.action == #selector(toggleReadFeedsFilter(_:)) {
return validateToggleReadFeeds(item)
2019-11-22 10:55:54 -06:00
}
if item.action == #selector(toggleReadArticlesFilter(_:)) {
return validateToggleReadArticles(item)
}
if item.action == #selector(sortArticlesByField(_:)) {
return validateSortArticlesByField(item)
2026-09-18 21:47:51 -07:00
}
if item.action == #selector(sortArticlesAscending(_:)) {
return validateSortDirection(item, direction: .orderedAscending)
2026-09-18 21:47:51 -07:00
}
if item.action == #selector(sortArticlesDescending(_:)) {
return validateSortDirection(item, direction: .orderedDescending)
2026-09-18 21:47:51 -07:00
}
2017-05-27 10:43:27 -07:00
return true
}
// MARK: - Actions
@IBAction func scrollOrGoToNextUnread(_ sender: Any?) {
2025-11-10 08:53:54 -08:00
guard let detailViewController else {
2019-02-18 13:10:16 -08:00
return
}
2025-11-10 08:53:54 -08:00
Task { @MainActor in
let canScroll = await detailViewController.canScrollDown()
NSCursor.setHiddenUntilMouseMoves(true)
2025-11-10 08:53:54 -08:00
if canScroll {
detailViewController.scrollPageDown(sender)
} else {
nextUnread(sender)
}
2017-12-20 13:39:31 -08:00
}
}
@IBAction func scrollUp(_ sender: Any?) {
2025-11-10 08:53:54 -08:00
guard let detailViewController else {
return
}
2025-11-10 08:53:54 -08:00
Task { @MainActor in
let canScroll = await detailViewController.canScrollUp()
if canScroll {
NSCursor.setHiddenUntilMouseMoves(true)
detailViewController.scrollPageUp(sender)
}
}
}
@IBAction func copyArticleURL(_ sender: Any?) {
guard let articles = selectedArticles else {
assertionFailure("Expected selectedArticles to be non-nil")
return
}
let links = articles.compactMap { $0.preferredLink }
if links.isEmpty {
assertionFailure("Expected at least one link")
return
}
URLPasteboardWriter.write(urlStrings: links, to: .general)
}
@IBAction func copyExternalURL(_ sender: Any?) {
guard let articles = selectedArticles else {
assertionFailure("Expected selectedArticles to be non-nil")
return
}
let links = articles.compactMap { $0.externalLink }
if links.isEmpty {
assertionFailure("Expected at least one link")
return
}
URLPasteboardWriter.write(urlStrings: links, to: .general)
}
@IBAction func openArticleInBrowser(_ sender: Any?) {
2017-05-27 10:43:27 -07:00
if let link = currentLink {
Browser.open(link, invertPreference: NSApp.currentEvent?.modifierFlags.contains(.shift) ?? false)
2026-01-02 17:50:35 -08:00
}
2017-05-27 10:43:27 -07:00
}
@IBAction func openInBrowser(_ sender: Any?) {
if AppDefaults.openInBrowserInBackground {
window?.makeKeyAndOrderFront(self)
}
openArticleInBrowser(sender)
}
@objc func openInAppBrowser(_ sender: Any?) {
2020-05-29 15:44:32 +05:30
// There is no In-App Browser for mac - so we use safari
openArticleInBrowser(sender)
}
@IBAction func openInBrowserUsingOppositeOfSettings(_ sender: Any?) {
if !AppDefaults.openInBrowserInBackground {
window?.makeKeyAndOrderFront(self)
}
if let link = currentLink {
Browser.open(link, inBackground: !AppDefaults.openInBrowserInBackground)
}
}
@IBAction func nextUnread(_ sender: Any?) {
2019-02-18 13:10:16 -08:00
guard let timelineViewController = currentTimelineViewController, let sidebarViewController = sidebarViewController else {
2017-05-27 10:43:27 -07:00
return
}
2018-09-04 21:18:59 -07:00
// Flush coalesced unread-count updates so folder counts are current.
CoalescingQueue.standard.performCallsImmediately()
2018-09-04 21:18:59 -07:00
NSCursor.setHiddenUntilMouseMoves(true)
2019-02-18 13:10:16 -08:00
// TODO: handle search mode
if timelineViewController.canGoToNextUnread(wrappingToTop: false) {
goToNextUnreadInTimeline(wrappingToTop: false)
2026-01-02 11:57:55 -08:00
} else if sidebarViewController.canGoToNextUnread(wrappingToTop: true) {
sidebarViewController.goToNextUnread(wrappingToTop: true)
// If we ended up on the same timelineViewController, we may need to wrap
// around to the top of its contents.
if timelineViewController.canGoToNextUnread(wrappingToTop: true) {
goToNextUnreadInTimeline(wrappingToTop: true)
}
}
}
@IBAction func markAllAsRead(_ sender: Any?) {
2019-02-18 13:10:16 -08:00
currentTimelineViewController?.markAllAsRead()
2017-05-27 10:43:27 -07:00
}
2017-11-05 21:27:34 -08:00
@IBAction func toggleRead(_ sender: Any?) {
2019-02-18 13:10:16 -08:00
currentTimelineViewController?.toggleReadStatusForSelectedArticles()
}
2017-11-05 21:27:34 -08:00
2019-02-18 13:10:16 -08:00
@IBAction func markRead(_ sender: Any?) {
currentTimelineViewController?.markSelectedArticlesAsRead(sender)
2017-11-05 21:27:34 -08:00
}
@IBAction func markUnread(_ sender: Any?) {
2019-02-18 13:10:16 -08:00
currentTimelineViewController?.markSelectedArticlesAsUnread(sender)
}
@IBAction func toggleStarred(_ sender: Any?) {
2019-02-18 13:10:16 -08:00
currentTimelineViewController?.toggleStarredStatusForSelectedArticles()
}
2019-09-18 18:15:55 -05:00
@IBAction func toggleArticleExtractor(_ sender: Any?) {
2025-11-05 11:22:10 -08:00
2019-09-18 18:15:55 -05:00
guard let currentLink = currentLink, let article = oneSelectedArticle else {
return
}
2019-09-19 17:25:36 -05:00
defer {
makeToolbarValidate()
}
2025-11-05 11:22:10 -08:00
if articleExtractor?.state == .failedToParse {
startArticleExtractorForCurrentLink()
return
}
2025-11-05 11:22:10 -08:00
2019-09-19 17:25:36 -05:00
guard articleExtractor?.state != .processing else {
articleExtractor?.cancel()
articleExtractor = nil
isShowingExtractedArticle = false
detailViewController?.setState(DetailState.article(article, nil), mode: timelineSourceMode)
2019-09-19 17:25:36 -05:00
return
}
2025-11-05 11:22:10 -08:00
2019-09-19 17:25:36 -05:00
guard !isShowingExtractedArticle else {
isShowingExtractedArticle = false
detailViewController?.setState(DetailState.article(article, nil), mode: timelineSourceMode)
2019-09-18 18:15:55 -05:00
return
}
2025-11-05 11:22:10 -08:00
2019-09-18 18:15:55 -05:00
if let articleExtractor = articleExtractor, let extractedArticle = articleExtractor.article {
if currentLink == articleExtractor.articleLink {
2019-09-19 17:25:36 -05:00
isShowingExtractedArticle = true
let detailState = DetailState.extracted(article, extractedArticle, nil)
2019-09-18 18:15:55 -05:00
detailViewController?.setState(detailState, mode: timelineSourceMode)
}
} else {
2019-09-21 15:03:42 -05:00
startArticleExtractorForCurrentLink()
2019-09-18 18:15:55 -05:00
}
2025-11-05 11:22:10 -08:00
2019-09-18 18:15:55 -05:00
}
@IBAction func markAllAsReadAndGoToNextUnread(_ sender: Any?) {
2026-01-02 17:50:35 -08:00
currentTimelineViewController?.markAllAsRead {
self.nextUnread(sender)
}
}
@IBAction func markUnreadAndGoToNextUnread(_ sender: Any?) {
markUnread(sender)
nextUnread(sender)
}
2017-12-20 20:51:17 -08:00
@IBAction func markReadAndGoToNextUnread(_ sender: Any?) {
markUnread(sender)
nextUnread(sender)
}
@IBAction func markOlderArticlesAsRead(_ sender: Any?) {
currentTimelineViewController?.markOlderArticlesRead()
}
2025-11-05 11:22:10 -08:00
@IBAction func markAboveArticlesAsRead(_ sender: Any?) {
currentTimelineViewController?.markAboveArticlesRead()
}
@IBAction func markBelowArticlesAsRead(_ sender: Any?) {
currentTimelineViewController?.markBelowArticlesRead()
2017-11-19 16:28:26 -08:00
}
@IBAction func navigateToTimeline(_ sender: Any?) {
2019-02-18 13:10:16 -08:00
currentTimelineViewController?.focus()
}
@IBAction func navigateToSidebar(_ sender: Any?) {
sidebarViewController?.focus()
}
@IBAction func navigateToDetail(_ sender: Any?) {
detailViewController?.focus()
}
2025-11-05 11:22:10 -08:00
@IBAction func goToPreviousSubscription(_ sender: Any?) {
sidebarViewController?.outlineView.selectPreviousRow(sender)
}
@IBAction func goToNextSubscription(_ sender: Any?) {
sidebarViewController?.outlineView.selectNextRow(sender)
}
@IBAction func gotoToday(_ sender: Any?) {
sidebarViewController?.gotoToday(sender)
}
@IBAction func gotoAllUnread(_ sender: Any?) {
sidebarViewController?.gotoAllUnread(sender)
}
@IBAction func gotoStarred(_ sender: Any?) {
sidebarViewController?.gotoStarred(sender)
}
@IBAction func toolbarShowShareMenu(_ sender: Any?) {
guard let selectedArticles = selectedArticles, !selectedArticles.isEmpty else {
assertionFailure("Expected toolbarShowShareMenu to be called only when there are selected articles.")
return
}
guard let shareToolbarItem = shareToolbarItem else {
assertionFailure("Expected toolbarShowShareMenu to be called only by the Share item in the toolbar.")
return
}
// In the toolbar's Text Only mode or overflow menu the item's view isn't on-window, so anchor the picker to the window instead.
let anchorView: NSView
let anchorRect: NSRect
if let view = shareToolbarItem.view, view.window != nil {
anchorView = view
anchorRect = view.bounds
} else if let contentView = window?.contentView {
anchorView = contentView
anchorRect = NSRect(x: contentView.frame.width / 2.0, y: contentView.frame.height - 4, width: 1, height: 1)
} else {
return
}
let sortedArticles = selectedArticles.sortedByDate(.orderedAscending)
let items = sortedArticles.map { ArticlePasteboardWriter(article: $0) }
detailViewController?.fetchSelectedHTML { selectedHTML in
self.sharingServicePickerDelegate?.selectedHTML = selectedHTML
let sharingServicePicker = NSSharingServicePicker(items: items)
sharingServicePicker.delegate = self.sharingServicePickerDelegate
sharingServicePicker.show(relativeTo: anchorRect, of: anchorView, preferredEdge: .minY)
}
}
@IBAction func moveFocusToSearchField(_ sender: Any?) {
// The search field lives in the toolbar — show it if hidden.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4896>
if let toolbar = window?.toolbar, !toolbar.isVisible {
toolbar.isVisible = true
}
guard let searchField = currentSearchField else {
return
}
window?.makeFirstResponder(searchField)
}
2019-11-22 10:55:54 -06:00
2020-03-15 18:02:55 -05:00
@IBAction func cleanUp(_ sender: Any?) {
timelineContainerViewController?.cleanUp()
}
2025-11-05 11:22:10 -08:00
@IBAction func toggleReadFeedsFilter(_ sender: Any?) {
2019-11-22 10:55:54 -06:00
sidebarViewController?.toggleReadFilter()
}
2025-11-05 11:22:10 -08:00
@IBAction func toggleReadArticlesFilter(_ sender: Any?) {
timelineContainerViewController?.toggleReadFilter()
}
2025-11-05 11:22:10 -08:00
@IBAction func sortArticlesByField(_ sender: NSMenuItem) {
// The menu item’s identifier is the ArticleSortKey raw value.
guard let identifier = sender.identifier, let key = ArticleSortKey(rawValue: identifier.rawValue) else {
return
}
timelineContainerViewController?.sortBy(key: key)
2026-09-18 21:47:51 -07:00
}
@IBAction func sortArticlesAscending(_ sender: Any?) {
timelineContainerViewController?.setSortDirection(.orderedAscending)
2026-09-18 21:47:51 -07:00
}
@IBAction func sortArticlesDescending(_ sender: Any?) {
timelineContainerViewController?.setSortDirection(.orderedDescending)
2026-09-18 21:47:51 -07:00
}
2021-09-08 19:58:40 -05:00
@objc func selectArticleTheme(_ menuItem: NSMenuItem) {
ArticleThemesManager.shared.currentThemeName = menuItem.title
}
}
// MARK: NSWindowDelegate
extension MainWindowController: NSWindowDelegate {
2025-11-05 11:22:10 -08:00
func window(_ window: NSWindow, willEncodeRestorableState coder: NSCoder) {
let state = savableState()
Self.logger.debug("MainWindowController: willEncodeRestorableState: \(state)")
coder.encode(state, forKey: UserInfoKey.windowState)
}
func window(_ window: NSWindow, didDecodeRestorableState coder: NSCoder) {
guard let state = coder.decodeObject(of: MainWindowState.self, forKey: UserInfoKey.windowState) else {
Self.logger.debug("MainWindowController: failed to decode restorable state")
return
}
Self.logger.debug("MainWindowController: didDecodeRestorableState: \(state)")
restoreState(from: state)
}
func windowWillClose(_ notification: Notification) {
Self.logger.debug("MainWindowController: windowWillClose")
detailViewController?.stopMediaPlayback()
appDelegate.removeMainWindow(self)
}
}
2019-02-17 18:46:28 -08:00
// MARK: - SidebarDelegate
extension MainWindowController: SidebarDelegate {
func sidebarSelectionDidChange(_: SidebarViewController, selectedObjects: [AnyObject]?) {
// Don’t update the timeline if it already has those objects.
let representedObjectsAreTheSame = timelineContainerViewController?.regularTimelineViewControllerHasRepresentedObjects(selectedObjects) ?? false
if !representedObjectsAreTheSame {
timelineContainerViewController?.setRepresentedObjects(selectedObjects, mode: .regular)
forceSearchToEnd()
}
2019-02-17 18:46:28 -08:00
updateWindowTitle()
NotificationCenter.default.post(name: .InspectableObjectsDidChange, object: nil)
}
func unreadCount(for representedObject: AnyObject) -> Int {
guard let timelineViewController = regularTimelineViewController else {
return 0
}
guard timelineViewController.representsThisObjectOnly(representedObject) else {
return 0
}
return timelineViewController.unreadCount
}
2025-11-05 11:22:10 -08:00
func sidebarInvalidatedRestorationState(_: SidebarViewController) {
Self.logger.debug("MainWindowController: sidebarInvalidatedRestorationState")
invalidateRestorableState()
}
2019-02-17 18:46:28 -08:00
}
// MARK: - TimelineContainerViewControllerDelegate
extension MainWindowController: TimelineContainerViewControllerDelegate {
func timelineSelectionDidChange(_: TimelineContainerViewController, articles: [Article]?, mode: TimelineSourceMode) {
2019-10-03 15:49:27 -05:00
activityManager.invalidateReading()
2025-11-05 11:22:10 -08:00
2019-09-19 17:25:36 -05:00
articleExtractor?.cancel()
articleExtractor = nil
isShowingExtractedArticle = false
makeToolbarValidate()
2025-11-05 11:22:10 -08:00
let detailState: DetailState
if let articles = articles {
2019-09-21 15:03:42 -05:00
if articles.count == 1 {
2019-11-15 06:19:14 -06:00
activityManager.reading(feed: nil, article: articles.first)
if articles.first?.feed?.readerViewAlwaysEnabled == true {
2019-09-21 15:03:42 -05:00
detailState = .loading
startArticleExtractorForCurrentLink()
} else {
detailState = .article(articles.first!, restoreArticleWindowScrollY)
restoreArticleWindowScrollY = nil
2019-09-21 15:03:42 -05:00
}
} else {
detailState = .multipleSelection
}
} else {
detailState = .noSelection
}
2019-09-18 18:15:55 -05:00
detailViewController?.setState(detailState, mode: mode)
updateStatusBarLink()
}
2025-11-03 08:55:25 -08:00
func timelineRequestedFeedSelection(_: TimelineContainerViewController, feed: Feed) {
sidebarViewController?.selectFeed(feed)
}
2025-11-05 11:22:10 -08:00
func timelineInvalidatedRestorationState(_: TimelineContainerViewController) {
invalidateRestorableState()
}
2025-11-05 11:22:10 -08:00
}
// MARK: - NSSearchFieldDelegate
extension MainWindowController: NSSearchFieldDelegate {
func searchFieldDidStartSearching(_ sender: NSSearchField) {
startSearchingIfNeeded()
}
func searchFieldDidEndSearching(_ sender: NSSearchField) {
stopSearchingIfNeeded()
}
@IBAction func runSearch(_ sender: NSSearchField) {
if sender.stringValue == "" {
return
}
startSearchingIfNeeded()
handleSearchFieldTextChange(sender)
}
private func handleSearchFieldTextChange(_ searchField: NSSearchField) {
let s = searchField.stringValue
if s == searchString {
return
}
searchString = s
updateSmartFeed()
}
func updateSmartFeed() {
guard timelineSourceMode == .search, let searchString = searchString else {
return
}
if searchString == lastSentSearchString {
return
}
lastSentSearchString = searchString
let smartFeed = SmartFeed(delegate: SearchFeedDelegate(searchString: searchString))
timelineContainerViewController?.setRepresentedObjects([smartFeed], mode: .search)
searchSmartFeed = smartFeed
2020-11-19 16:21:51 -06:00
updateWindowTitle()
}
func forceSearchToEnd() {
timelineSourceMode = .regular
searchString = nil
lastSentSearchString = nil
if let searchField = currentSearchField {
searchField.stringValue = ""
}
2020-11-19 16:21:51 -06:00
updateWindowTitle()
}
private func startSearchingIfNeeded() {
timelineSourceMode = .search
2020-11-19 16:21:51 -06:00
updateWindowTitle()
}
private func stopSearchingIfNeeded() {
searchString = nil
lastSentSearchString = nil
timelineSourceMode = .regular
timelineContainerViewController?.setRepresentedObjects(nil, mode: .search)
2020-11-19 16:21:51 -06:00
updateWindowTitle()
}
}
2019-09-18 18:15:55 -05:00
// MARK: - ArticleExtractorDelegate
extension MainWindowController: ArticleExtractorDelegate {
2025-11-05 11:22:10 -08:00
2019-09-18 18:15:55 -05:00
func articleExtractionDidFail(with: Error) {
makeToolbarValidate()
}
2025-11-05 11:22:10 -08:00
2019-09-18 18:15:55 -05:00
func articleExtractionDidComplete(extractedArticle: ExtractedArticle) {
2019-09-19 17:25:36 -05:00
if let article = oneSelectedArticle, articleExtractor?.state != .cancelled {
isShowingExtractedArticle = true
let detailState = DetailState.extracted(article, extractedArticle, restoreArticleWindowScrollY)
restoreArticleWindowScrollY = nil
2019-09-18 18:15:55 -05:00
detailViewController?.setState(detailState, mode: timelineSourceMode)
2019-09-19 17:25:36 -05:00
makeToolbarValidate()
2019-09-18 18:15:55 -05:00
}
}
2025-11-05 11:22:10 -08:00
2019-09-18 18:15:55 -05:00
}
// MARK: - Scripting Access
/*
the ScriptingMainWindowController protocol exposes a narrow set of accessors with
internal visibility which are very similar to some private vars.
2025-11-05 11:22:10 -08:00
These would be unnecessary if the similar accessors were marked internal rather than private,
but for now, we'll keep the stratification of visibility
*/
2026-01-01 18:07:54 -08:00
extension MainWindowController: ScriptingMainWindowController {
2026-01-08 09:14:51 -08:00
var scriptingCurrentArticle: Article? {
oneSelectedArticle
}
2026-01-08 09:14:51 -08:00
var scriptingSelectedArticles: [Article] {
selectedArticles ?? []
}
var scriptingSelectedFeeds: [Feed] {
selectedObjectsInSidebar()?.compactMap { $0 as? Feed } ?? []
}
}
// MARK: - DetailViewControllerDelegate
extension MainWindowController: DetailViewControllerDelegate {
func detailViewController(_ detailViewController: DetailViewController, mouseoverLinkDidChange link: String?) {
mouseoverLink = link
}
}
// MARK: - MainWindowStatusBarViewDelegate
extension MainWindowController: MainWindowStatusBarViewDelegate {
func statusBarViewGearMenu(_ statusBarView: MainWindowStatusBarView) -> NSMenu? {
guard let menu = sidebarViewController?.statusBarMenu() else {
return nil
}
var index = 0
if AccountManager.shared.canRefresh {
menu.insertItem(withTitle: NSLocalizedString("Refresh", comment: "Refresh"), action: #selector(AppDelegate.refreshAll(_:)), keyEquivalent: "", at: index)
index += 1
}
let isSidebarHidden = sidebarSplitViewItem?.isCollapsed ?? false
let sidebarTitle = isSidebarHidden ? NSLocalizedString("Show Sidebar", comment: "Command") : NSLocalizedString("Hide Sidebar", comment: "Command")
menu.insertItem(withTitle: sidebarTitle, action: #selector(NSSplitViewController.toggleSidebar(_:)), keyEquivalent: "", at: index)
menu.insertItem(NSMenuItem.separator(), at: index + 1)
return menu
}
func statusBarView(_ statusBarView: MainWindowStatusBarView, moveSidebarDividerTo position: CGFloat) {
guard let splitView = splitViewController?.splitView else {
return
}
let positionInWindow = statusBarView.convert(NSPoint(x: position, y: 0), to: nil)
let positionInSplitView = splitView.convert(positionInWindow, from: nil)
splitView.setPosition(positionInSplitView.x, ofDividerAt: 0)
}
}
// MARK: - NSToolbarDelegate
extension NSToolbarItem.Identifier {
static let newFeed = NSToolbarItem.Identifier("newFeed")
static let newFolder = NSToolbarItem.Identifier("newFolder")
static let refresh = NSToolbarItem.Identifier("refresh")
2020-08-09 11:46:53 -05:00
static let newSidebarItemMenu = NSToolbarItem.Identifier("newSidebarItemMenu")
static let timelineTrackingSeparator = NSToolbarItem.Identifier("timelineTrackingSeparator")
static let search = NSToolbarItem.Identifier("search")
static let markAllAsRead = NSToolbarItem.Identifier("markAllAsRead")
static let toggleReadArticlesFilter = NSToolbarItem.Identifier("toggleReadArticlesFilter")
static let nextUnread = NSToolbarItem.Identifier("nextUnread")
static let markRead = NSToolbarItem.Identifier("markRead")
static let markStar = NSToolbarItem.Identifier("markStar")
static let readerView = NSToolbarItem.Identifier("readerView")
static let openInBrowser = NSToolbarItem.Identifier("openInBrowser")
static let share = NSToolbarItem.Identifier("share")
2021-09-08 19:58:40 -05:00
static let articleThemeMenu = NSToolbarItem.Identifier("articleThemeMenu")
2020-08-10 03:58:19 -05:00
static let cleanUp = NSToolbarItem.Identifier("cleanUp")
}
extension MainWindowController: NSToolbarDelegate {
func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
2020-08-10 03:58:19 -05:00
2024-11-22 20:08:26 -08:00
switch itemIdentifier {
2020-08-10 03:58:19 -05:00
2024-11-22 20:08:26 -08:00
case .refresh:
let title = NSLocalizedString("Refresh", comment: "Refresh")
2025-11-19 10:38:18 -08:00
return buildToolbarButton(.refresh, title, Assets.Images.refresh, "refreshAll:")
2020-08-11 21:03:19 -05:00
2024-11-22 20:08:26 -08:00
case .newSidebarItemMenu:
let toolbarItem = NSMenuToolbarItem(itemIdentifier: .newSidebarItemMenu)
2025-11-19 10:38:18 -08:00
toolbarItem.image = Assets.Images.addNewSidebarItem
2024-11-22 20:08:26 -08:00
let description = NSLocalizedString("Add Item", comment: "Add Item")
toolbarItem.toolTip = description
toolbarItem.label = description
toolbarItem.menu = buildNewSidebarItemMenu()
return toolbarItem
2020-08-10 03:58:19 -05:00
2024-11-22 20:08:26 -08:00
case .markAllAsRead:
let title = NSLocalizedString("Mark All as Read", comment: "Command")
2025-11-19 10:38:18 -08:00
return buildToolbarButton(.markAllAsRead, title, Assets.Images.markAllAsRead, "markAllAsRead:")
2020-08-10 03:58:19 -05:00
2024-11-22 20:08:26 -08:00
case .toggleReadArticlesFilter:
let title = NSLocalizedString("Read Articles Filter", comment: "Read Articles Filter")
2025-11-19 10:38:18 -08:00
return buildToolbarButton(.toggleReadArticlesFilter, title, Assets.Images.filterInactive, "toggleReadArticlesFilter:")
2024-11-22 20:08:26 -08:00
case .timelineTrackingSeparator:
2026-09-19 10:44:51 -07:00
// Only the standard layout has a vertical divider between the timeline and the article view.
// Column layout gets a hidden placeholder so the identifier stays in the saved configuration
// and the separator returns when the layout does — one toolbar, one customization.
2026-09-19 10:44:51 -07:00
guard timelineLayout == .standard, let splitView = splitViewController?.splitView else {
let placeholder = NSToolbarItem(itemIdentifier: .timelineTrackingSeparator)
placeholder.isHidden = true
// Hidden in the toolbar, but the customization palette still lists it, so it needs a name and an image there.
let description = NSLocalizedString("Timeline Separator", comment: "Toolbar item")
placeholder.label = description
placeholder.paletteLabel = description
placeholder.image = NSImage(systemSymbolName: "rectangle.split.2x1", accessibilityDescription: description)
return placeholder
2026-09-19 10:44:51 -07:00
}
return NSTrackingSeparatorToolbarItem(identifier: .timelineTrackingSeparator, splitView: splitView, dividerIndex: 1)
2021-09-08 19:58:40 -05:00
2024-11-22 20:08:26 -08:00
case .markRead:
let title = NSLocalizedString("Mark Read", comment: "command")
2025-11-19 10:38:18 -08:00
return buildToolbarButton(.markRead, title, Assets.Images.readClosed, "toggleRead:")
2020-11-19 11:31:58 -06:00
2024-11-22 20:08:26 -08:00
case .markStar:
let title = NSLocalizedString("Star", comment: "Star")
return buildToolbarButton(.markStar, title, Assets.Images.starOpen, "toggleStarred:")
2020-08-10 03:58:19 -05:00
2024-11-22 20:08:26 -08:00
case .nextUnread:
let title = NSLocalizedString("Next Unread", comment: "Next Unread")
2025-11-19 10:38:18 -08:00
return buildToolbarButton(.nextUnread, title, Assets.Images.nextUnread, "nextUnread:")
2024-11-22 20:08:26 -08:00
case .readerView:
let toolbarItem = RSToolbarItem(itemIdentifier: .readerView)
toolbarItem.autovalidates = true
let description = NSLocalizedString("Reader View", comment: "Reader View")
toolbarItem.toolTip = description
toolbarItem.label = description
let button = ArticleExtractorButton()
button.action = #selector(toggleArticleExtractor(_:))
toolbarItem.view = button
toolbarItem.menuFormRepresentation = NSMenuItem(title: description, action: #selector(toggleArticleExtractor(_:)), keyEquivalent: "")
2024-11-22 20:08:26 -08:00
return toolbarItem
case .share:
let title = NSLocalizedString("Share", comment: "Share button")
2025-11-19 10:38:18 -08:00
return buildToolbarButton(.share, title, Assets.Images.share, "toolbarShowShareMenu:")
2024-11-22 20:08:26 -08:00
case .openInBrowser:
let title = NSLocalizedString("Open in Browser", comment: "Command")
2025-11-19 10:38:18 -08:00
return buildToolbarButton(.openInBrowser, title, Assets.Images.openInBrowser, "openArticleInBrowser:")
2024-11-22 20:08:26 -08:00
case .articleThemeMenu:
// Built per toolbar: a toolbar item belongs to one toolbar, and the toolbar is rebuilt on a layout switch.
let toolbarItem = NSMenuToolbarItem(itemIdentifier: .articleThemeMenu)
toolbarItem.image = Assets.Images.articleTheme
2024-11-22 20:08:26 -08:00
let description = NSLocalizedString("Article Theme", comment: "Article Theme")
toolbarItem.toolTip = description
toolbarItem.label = description
toolbarItem.menu = ArticleThemesManager.shared.makeArticleThemeMenu()
return toolbarItem
2024-11-22 20:08:26 -08:00
case .search:
let toolbarItem = NSSearchToolbarItem(itemIdentifier: .search)
let description = NSLocalizedString("Search", comment: "Search")
toolbarItem.toolTip = description
toolbarItem.label = description
return toolbarItem
case .cleanUp:
let title = NSLocalizedString("Clean Up", comment: "Clean Up button")
2025-11-19 10:38:18 -08:00
return buildToolbarButton(.cleanUp, title, Assets.Images.cleanUp, "cleanUp:")
2024-11-22 20:08:26 -08:00
default:
break
}
2024-11-22 20:08:26 -08:00
return nil
}
2025-11-05 11:22:10 -08:00
2020-08-10 03:58:19 -05:00
func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
[
2024-11-22 20:08:26 -08:00
NSToolbarItem.Identifier.toggleSidebar,
.refresh,
.newSidebarItemMenu,
.sidebarTrackingSeparator,
.markAllAsRead,
.toggleReadArticlesFilter,
.timelineTrackingSeparator,
.flexibleSpace,
.nextUnread,
.markRead,
.markStar,
.readerView,
.openInBrowser,
.share,
.articleThemeMenu,
.search,
.cleanUp
]
2020-08-10 03:58:19 -05:00
}
2024-11-22 20:08:26 -08:00
func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
[
2025-06-20 20:02:10 +08:00
NSToolbarItem.Identifier.toggleSidebar,
2024-11-22 20:08:26 -08:00
.flexibleSpace,
.refresh,
.newSidebarItemMenu,
.sidebarTrackingSeparator,
.markAllAsRead,
.toggleReadArticlesFilter,
.timelineTrackingSeparator,
.markRead,
.markStar,
.nextUnread,
.readerView,
.share,
.openInBrowser,
.flexibleSpace,
.search
]
}
2024-11-22 20:08:26 -08:00
func toolbarWillAddItem(_ notification: Notification) {
guard let item = notification.userInfo?["item"] as? NSToolbarItem else {
return
}
if item.itemIdentifier == .share, let button = item.view as? NSButton {
// The share button should send its action on mouse down, not mouse up.
button.sendAction(on: .leftMouseDown)
}
2024-11-22 20:08:26 -08:00
if item.itemIdentifier == .search, let searchItem = item as? NSSearchToolbarItem {
searchItem.searchField.delegate = self
searchItem.searchField.target = self
searchItem.searchField.action = #selector(runSearch(_:))
currentSearchField = searchItem.searchField
}
}
func toolbarDidRemoveItem(_ notification: Notification) {
guard let item = notification.userInfo?["item"] as? NSToolbarItem else {
return
}
2024-11-22 20:08:26 -08:00
if item.itemIdentifier == .search, let searchItem = item as? NSSearchToolbarItem {
searchItem.searchField.delegate = nil
searchItem.searchField.target = nil
searchItem.searchField.action = nil
currentSearchField = nil
}
}
}
2017-10-05 20:03:35 -07:00
// MARK: - Private
2017-05-27 10:43:27 -07:00
private extension MainWindowController {
2026-09-19 10:44:51 -07:00
// MARK: - Layout
2026-09-17 21:57:13 -07:00
2026-09-19 10:44:51 -07:00
/// Builds the split views for `layout` around the existing panes, replacing any current ones.
/// Selection, loaded articles, and the article view’s web view all survive, since the panes are reparented, not recreated.
func installSplitViewController(for layout: TimelineLayout) {
guard let window, let sidebarViewController, let timelineContainerViewController, let detailViewController else {
return
}
rememberCurrentLayoutGeometry()
let savedFrame = window.frame
let isSidebarHidden = sidebarSplitViewItem?.isCollapsed ?? false
let firstResponderView = window.firstResponder as? NSView
// The toolbar lives for the window’s life so the user’s customization is one thing. Only its tracking separators
// depend on the split views: they come out before the swap and go back in the same positions after,
// which also lets the timeline separator change kind for the new layout. The toolbar is hidden meanwhile —
// AppKit lays out its title area during the swap and reports conflicting constraints without the separators.
let trackingSeparators = removeTrackingSeparatorsFromToolbar()
let isToolbarVisible = window.toolbar?.isVisible ?? true
window.toolbar?.isVisible = false
2026-09-19 10:44:51 -07:00
detachSplitViewControllers()
let newSplitViewController: NSSplitViewController
switch layout {
case .standard:
newSplitViewController = makeStandardSplitViewController(sidebar: sidebarViewController, timeline: timelineContainerViewController, detail: detailViewController)
case .column:
2026-10-09 21:37:49 -07:00
let columnLayoutSplitViewControllers = makeColumnLayoutSplitViewControllers(sidebar: sidebarViewController, timeline: timelineContainerViewController, detail: detailViewController)
newSplitViewController = columnLayoutSplitViewControllers.split
contentSplitViewController = columnLayoutSplitViewControllers.content
2026-09-19 10:44:51 -07:00
}
splitViewController = newSplitViewController
timelineLayout = layout
if window.contentViewController !== mainWindowContentViewController {
window.contentViewController = mainWindowContentViewController
}
mainWindowContentViewController.splitViewController = newSplitViewController
2026-09-19 10:44:51 -07:00
if window.frame != savedFrame && !window.styleMask.contains(.fullScreen) {
window.setFrame(savedFrame, display: false)
}
if let toolbar = window.toolbar {
for (identifier, index) in trackingSeparators {
toolbar.insertItem(withItemIdentifier: identifier, at: index)
}
toolbar.isVisible = isToolbarVisible
} else {
window.toolbar = makeToolbar()
2026-09-19 21:29:18 -07:00
}
2026-09-19 10:44:51 -07:00
window.contentView?.layoutSubtreeIfNeeded()
applyRememberedGeometry()
sidebarSplitViewItem?.isCollapsed = isSidebarHidden
if let firstResponderView, firstResponderView.window === window {
2026-09-19 10:44:51 -07:00
window.makeFirstResponder(firstResponderView)
2026-09-19 21:29:18 -07:00
} else {
currentTimelineViewController?.focus()
2026-09-19 10:44:51 -07:00
}
window.recalculateKeyViewLoop()
observeSplitViewForStatusBar()
2026-09-19 10:44:51 -07:00
invalidateRestorableState()
}
/// Removes the sidebar and timeline tracking separators, returning their identifiers and positions in ascending order.
func removeTrackingSeparatorsFromToolbar() -> [(NSToolbarItem.Identifier, Int)] {
guard let toolbar = window?.toolbar else {
return []
}
let separatorIdentifiers: Set<NSToolbarItem.Identifier> = [.sidebarTrackingSeparator, .timelineTrackingSeparator]
let separators = toolbar.items.enumerated().filter { separatorIdentifiers.contains($0.element.itemIdentifier) }.map { ($0.element.itemIdentifier, $0.offset) }
for (_, index) in separators.reversed() {
toolbar.removeItem(at: index)
}
return separators
}
2026-09-19 10:44:51 -07:00
func detachSplitViewControllers() {
// NSSplitViewItem requires a parentless view controller, so remove the panes from the old split views first.
if let contentSplitViewController {
for item in contentSplitViewController.splitViewItems.reversed() {
contentSplitViewController.removeSplitViewItem(item)
}
}
if let splitViewController {
for item in splitViewController.splitViewItems.reversed() {
splitViewController.removeSplitViewItem(item)
}
}
contentSplitViewController = nil
splitViewController = nil
}
func makeStandardSplitViewController(sidebar: SidebarViewController, timeline: TimelineContainerViewController, detail: DetailViewController) -> NSSplitViewController {
let splitViewController = makeEmptySplitViewController(isVertical: true)
let sidebarItem = NSSplitViewItem(sidebarWithViewController: sidebar)
2026-09-17 21:57:13 -07:00
sidebarItem.holdingPriority = NSLayoutConstraint.Priority(Self.sidebarHoldingPriority)
2026-09-19 10:44:51 -07:00
let timelineItem = NSSplitViewItem(contentListWithViewController: timeline)
2026-09-17 21:57:13 -07:00
timelineItem.holdingPriority = NSLayoutConstraint.Priority(Self.timelineHoldingPriority)
2026-09-19 10:44:51 -07:00
if #available(macOS 26.0, *) {
timelineItem.automaticallyAdjustsSafeAreaInsets = true
}
let detailItem = NSSplitViewItem(viewController: detail)
detailItem.minimumThickness = CGFloat(Self.detailViewMinimumWidth)
if #unavailable(macOS 26.0) {
detailItem.titlebarSeparatorStyle = .line
}
2026-09-17 21:57:13 -07:00
splitViewController.splitViewItems = [sidebarItem, timelineItem, detailItem]
2026-09-19 10:44:51 -07:00
sidebar.splitViewItem = sidebarItem
2026-09-17 21:57:13 -07:00
return splitViewController
2017-05-27 10:43:27 -07:00
}
2026-10-09 21:37:49 -07:00
/// Returns the outer split (sidebar and content) and the content split (timeline above detail) it contains.
func makeColumnLayoutSplitViewControllers(sidebar: SidebarViewController, timeline: TimelineContainerViewController, detail: DetailViewController) -> (split: NSSplitViewController, content: NSSplitViewController) {
let contentSplitViewController = makeEmptySplitViewController(isVertical: false, splitView: ColumnLayoutSplitView())
contentSplitViewController.splitView.dividerStyle = .paneSplitter
2026-09-19 10:44:51 -07:00
let timelineItem = NSSplitViewItem(viewController: timeline)
timelineItem.holdingPriority = NSLayoutConstraint.Priority(Self.timelineHoldingPriority)
timelineItem.minimumThickness = Self.timelineMinimumHeight
timelineItem.canCollapse = false
let detailItem = NSSplitViewItem(viewController: detail)
detailItem.minimumThickness = Self.detailViewMinimumHeight
detailItem.canCollapse = false
contentSplitViewController.splitViewItems = [timelineItem, detailItem]
let splitViewController = makeEmptySplitViewController(isVertical: true)
let sidebarItem = NSSplitViewItem(sidebarWithViewController: sidebar)
sidebarItem.holdingPriority = NSLayoutConstraint.Priority(Self.sidebarHoldingPriority)
let contentItem = NSSplitViewItem(viewController: contentSplitViewController)
if #available(macOS 26.0, *) {
contentItem.automaticallyAdjustsSafeAreaInsets = true
2026-10-09 21:37:49 -07:00
} else {
2026-09-19 10:44:51 -07:00
contentItem.titlebarSeparatorStyle = .line
}
splitViewController.splitViewItems = [sidebarItem, contentItem]
sidebar.splitViewItem = sidebarItem
2026-10-09 21:37:49 -07:00
return (splitViewController, contentSplitViewController)
2026-09-19 10:44:51 -07:00
}
func makeEmptySplitViewController(isVertical: Bool, splitView: NSSplitView = NSSplitView()) -> NSSplitViewController {
2026-09-19 10:44:51 -07:00
let splitViewController = NSSplitViewController()
splitViewController.splitView = splitView
2026-09-19 10:44:51 -07:00
splitViewController.splitView.isVertical = isVertical
splitViewController.splitView.dividerStyle = .thin
splitViewController.splitView.wantsLayer = true
return splitViewController
}
func makeToolbar() -> NSToolbar {
let toolbar = NSToolbar(identifier: Self.toolbarIdentifier)
2026-09-19 10:44:51 -07:00
toolbar.allowsUserCustomization = true
toolbar.autosavesConfiguration = true
toolbar.displayMode = .iconOnly
toolbar.delegate = self
return toolbar
}
2019-02-18 13:10:16 -08:00
var currentTimelineViewController: TimelineViewController? {
return timelineContainerViewController?.currentTimelineViewController
2017-05-27 10:43:27 -07:00
}
var regularTimelineViewController: TimelineViewController? {
return timelineContainerViewController?.regularTimelineViewController
}
var sidebarSplitViewItem: NSSplitViewItem? {
2026-09-19 10:44:51 -07:00
splitViewController?.splitViewItems.first
2017-05-27 10:43:27 -07:00
}
2025-11-05 11:22:10 -08:00
2017-05-27 10:43:27 -07:00
var selectedArticles: [Article]? {
2019-02-18 13:10:16 -08:00
return currentTimelineViewController?.selectedArticles
2017-05-27 10:43:27 -07:00
}
2017-05-27 10:43:27 -07:00
var oneSelectedArticle: Article? {
if let articles = selectedArticles {
return articles.count == 1 ? articles[0] : nil
2017-05-27 10:43:27 -07:00
}
return nil
2017-05-27 10:43:27 -07:00
}
2017-05-27 10:43:27 -07:00
var currentLink: String? {
return oneSelectedArticle?.preferredLink
2017-05-27 10:43:27 -07:00
}
// MARK: - State Restoration
2025-11-05 11:22:10 -08:00
func savableState() -> MainWindowState {
let isFullScreen = window?.styleMask.contains(.fullScreen) ?? false
let isSidebarHidden = sidebarSplitViewItem?.isCollapsed ?? false
2026-01-08 09:07:53 -08:00
2026-09-19 10:44:51 -07:00
rememberCurrentLayoutGeometry()
return MainWindowState(isFullScreen: isFullScreen,
2026-09-19 10:44:51 -07:00
splitViewWidths: rememberedStandardLayoutWidths,
columnLayoutTimelineHeight: rememberedColumnLayoutTimelineHeight,
isSidebarHidden: isSidebarHidden,
sidebarWindowState: sidebarViewController?.windowState,
timelineWindowState: timelineContainerViewController?.windowState,
detailWindowState: detailViewController?.windowState)
}
2026-09-19 10:44:51 -07:00
/// Reads the live split view positions into the remembered geometry for the current layout.
/// The sidebar is shared by both layouts, so its width is always refreshed.
func rememberCurrentLayoutGeometry() {
guard let splitView = splitViewController?.splitView, let window, let sidebarView = splitView.arrangedSubviews.first else {
return
}
let dividerThickness = splitView.dividerThickness
let isSidebarHidden = sidebarSplitViewItem?.isCollapsed ?? false
let visibleSidebarWidth = isSidebarHidden ? 0.0 : sidebarView.frame.width
// While collapsed, keep the last visible width so a rebuilt split view can reopen the sidebar at that width.
let previousSidebarWidth = rememberedStandardLayoutWidths.count == 3 ? rememberedStandardLayoutWidths[0] : 0
let sidebarWidth = isSidebarHidden ? previousSidebarWidth : Int(floor(visibleSidebarWidth))
2026-09-19 10:44:51 -07:00
switch timelineLayout {
case .standard:
guard splitView.arrangedSubviews.count == 3 else {
return
}
let detailWidth = splitView.arrangedSubviews[2].frame.width
// Starting with macOS 26, timelineWidth has to be calculated —
// because its width is greater than its apparent width,
// so that things can slide under the sidebar.
let dividerCount: CGFloat = isSidebarHidden ? 1.0 : 2.0
let timelineWidth = window.frame.width - (visibleSidebarWidth + detailWidth + (dividerThickness * dividerCount))
rememberedStandardLayoutWidths = [sidebarWidth, Int(floor(timelineWidth)), Int(floor(detailWidth))]
2026-09-19 10:44:51 -07:00
case .column:
if rememberedStandardLayoutWidths.count == 3 {
rememberedStandardLayoutWidths[0] = sidebarWidth
2026-09-19 10:44:51 -07:00
} else {
rememberedStandardLayoutWidths = [sidebarWidth, 0, 0]
2026-09-19 10:44:51 -07:00
}
if let timelineView = contentSplitViewController?.splitView.arrangedSubviews.first {
rememberedColumnLayoutTimelineHeight = Int(floor(timelineView.frame.height))
}
}
}
func applyRememberedGeometry() {
guard let splitView = splitViewController?.splitView else {
return
}
let widths = rememberedStandardLayoutWidths
switch timelineLayout {
case .standard:
guard widths.count == 3 else {
return
}
let sidebarWidth = CGFloat(widths[0])
let timelineWidth = CGFloat(widths[1])
2026-10-09 11:36:58 -07:00
// The sidebar is positioned expanded here and collapsed by the caller afterward. A zero sidebar width
// comes from state saved before the collapsed width was kept (7.1.x) — keep the default width.
if sidebarWidth > 0 {
splitView.setPosition(sidebarWidth, ofDividerAt: 0)
}
2026-09-19 10:44:51 -07:00
// A zero timeline width means the standard layout has never been laid out — leave it to the holding priorities.
if timelineWidth > 0 {
let secondDividerPosition = sidebarWidth > 0 ? sidebarWidth + splitView.dividerThickness + timelineWidth : timelineWidth
splitView.setPosition(secondDividerPosition, ofDividerAt: 1)
}
case .column:
2026-10-09 11:36:58 -07:00
if widths.count == 3 && widths[0] > 0 {
2026-09-19 10:44:51 -07:00
splitView.setPosition(CGFloat(widths[0]), ofDividerAt: 0)
}
guard let contentSplitView = contentSplitViewController?.splitView else {
return
}
let timelineHeight: CGFloat
if rememberedColumnLayoutTimelineHeight > 0 {
timelineHeight = CGFloat(rememberedColumnLayoutTimelineHeight)
} else {
timelineHeight = floor(contentSplitView.bounds.height * Self.defaultColumnLayoutTimelineHeightFraction)
}
contentSplitView.setPosition(timelineHeight, ofDividerAt: 0)
}
}
func restoreState(from state: MainWindowState) {
if state.isFullScreen {
// Defer the toggle — during launch the window isn't on screen yet,
// and AppKit ignores toggleFullScreen for windows not yet on screen.
Task { @MainActor in
guard let window = self.window, !window.styleMask.contains(.fullScreen) else {
return
}
window.toggleFullScreen(nil)
}
}
restoreSplitViewState(from: state)
2025-11-05 11:22:10 -08:00
sidebarViewController?.restoreState(from: state.sidebarWindowState)
2025-11-05 11:22:10 -08:00
timelineContainerViewController?.restoreState(from: state.timelineWindowState)
restoreArticleWindowScrollY = state.detailWindowState?.windowScrollY
2025-08-14 21:33:04 -07:00
let isShowingExtractedArticle = state.detailWindowState?.isShowingExtractedArticle ?? false
if isShowingExtractedArticle {
startArticleExtractorForCurrentLink()
}
}
/// Restore state using pre-secure-state-restoration data.
///
/// It’s up to the caller to call this only when:
/// 1. Legacy state exists, and
/// 2. Secure state data does not exist.
///
/// TODO: delete this for NetNewsWire 7.
func restoreLegacyState(from state: [AnyHashable: Any]) {
if let fullScreen = state[UserInfoKey.windowFullScreenState] as? Bool, fullScreen {
window?.toggleFullScreen(self)
}
restoreLegacySplitViewState(from: state)
sidebarViewController?.restoreLegacyState(from: state)
let articleWindowScrollY = state[UserInfoKey.articleWindowScrollY] as? CGFloat
restoreArticleWindowScrollY = articleWindowScrollY
timelineContainerViewController?.restoreLegacyState(from: state)
let isShowingExtractedArticle = state[UserInfoKey.isShowingExtractedArticle] as? Bool ?? false
if isShowingExtractedArticle {
restoreArticleWindowScrollY = articleWindowScrollY
startArticleExtractorForCurrentLink()
}
}
// MARK: - Command Validation
2025-11-05 11:22:10 -08:00
func canCopyArticleURL() -> Bool {
guard let selectedArticles else {
return false
}
for article in selectedArticles {
if article.preferredLink != nil {
return true
}
}
return false
}
2025-11-05 11:22:10 -08:00
func canCopyExternalURL() -> Bool {
guard let selectedArticles else {
return false
}
for article in selectedArticles {
if article.externalLink != nil {
return true
}
}
return false
}
func canGoToNextUnread(wrappingToTop wrapping: Bool = false) -> Bool {
2025-11-05 11:22:10 -08:00
2019-02-18 13:10:16 -08:00
guard let timelineViewController = currentTimelineViewController, let sidebarViewController = sidebarViewController else {
2017-05-27 10:43:27 -07:00
return false
}
// When the only unread article in the account is the one already selected, Next Unread has nowhere to go.
// This state persists on Mac when the selected article is marked read on selection and then manually marked unread again.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5008>
if AccountManager.shared.unreadCount == 1, timelineViewController.selectedArticles.count == 1, let article = timelineViewController.selectedArticles.first, !article.status.read {
return false
}
2019-02-18 13:10:16 -08:00
// TODO: handle search mode
return timelineViewController.canGoToNextUnread(wrappingToTop: wrapping) || sidebarViewController.canGoToNextUnread(wrappingToTop: wrapping)
2017-05-27 10:43:27 -07:00
}
2025-11-05 11:22:10 -08:00
2017-05-27 10:43:27 -07:00
func canMarkAllAsRead() -> Bool {
2025-11-05 11:22:10 -08:00
2019-02-18 13:10:16 -08:00
return currentTimelineViewController?.canMarkAllAsRead() ?? false
2017-05-27 10:43:27 -07:00
}
2025-11-05 11:22:10 -08:00
func validateToggleRead(_ item: NSValidatedUserInterfaceItem) -> Bool {
2017-11-05 21:27:34 -08:00
2019-02-18 13:10:16 -08:00
let validationStatus = currentTimelineViewController?.markReadCommandStatus() ?? .canDoNothing
let markingRead: Bool
let result: Bool
2025-11-05 11:22:10 -08:00
switch validationStatus {
case .canMark:
markingRead = true
result = true
case .canUnmark:
markingRead = false
result = true
case .canDoNothing:
markingRead = true
result = false
}
2025-11-05 11:22:10 -08:00
let commandName = markingRead ? NSLocalizedString("Mark as Read", comment: "Command") : NSLocalizedString("Mark as Unread", comment: "Command")
2025-11-05 11:22:10 -08:00
if let toolbarItem = item as? NSToolbarItem {
toolbarItem.toolTip = commandName
// Text Only toolbar mode shows the label and menu form representation, so they need to track state too.
let shortName = markingRead ? NSLocalizedString("Mark Read", comment: "command") : NSLocalizedString("Mark Unread", comment: "command")
toolbarItem.label = shortName
toolbarItem.menuFormRepresentation?.title = shortName
}
2025-11-05 11:22:10 -08:00
if let menuItem = item as? NSMenuItem {
menuItem.title = commandName
}
2025-11-05 11:22:10 -08:00
2024-11-22 20:08:26 -08:00
if let toolbarItem = item as? NSToolbarItem, let button = toolbarItem.view as? NSButton {
2025-11-19 10:38:18 -08:00
button.image = markingRead ? Assets.Images.readClosed : Assets.Images.readOpen
}
2025-11-05 11:22:10 -08:00
return result
2017-11-05 21:27:34 -08:00
}
2019-09-18 18:15:55 -05:00
func validateToggleArticleExtractor(_ item: NSValidatedUserInterfaceItem) -> Bool {
guard !AppDefaults.isDeveloperBuild else {
return false
}
2021-04-09 07:47:14 +08:00
2024-11-22 20:08:26 -08:00
guard let toolbarItem = item as? NSToolbarItem, let toolbarButton = toolbarItem.view as? ArticleExtractorButton else {
if let menuItem = item as? NSMenuItem {
menuItem.state = isShowingExtractedArticle ? .on : .off
}
return currentLink != nil
}
2019-09-19 17:25:36 -05:00
2025-11-02 15:12:00 -08:00
if currentTimelineViewController?.selectedArticles.first?.feed != nil {
2024-11-22 20:08:26 -08:00
toolbarButton.isEnabled = true
}
2024-11-22 20:08:26 -08:00
guard let state = articleExtractor?.state else {
toolbarButton.buttonState = .off
return currentLink != nil
}
2024-11-22 20:08:26 -08:00
switch state {
case .processing:
toolbarButton.buttonState = .animated
case .failedToParse:
toolbarButton.buttonState = .error
case .ready, .cancelled, .complete:
toolbarButton.buttonState = isShowingExtractedArticle ? .on : .off
2019-09-19 17:25:36 -05:00
}
return state != .processing
2019-09-18 18:15:55 -05:00
}
func canMarkAboveArticlesAsRead() -> Bool {
return currentTimelineViewController?.canMarkAboveArticlesAsRead() ?? false
}
func canMarkBelowArticlesAsRead() -> Bool {
return currentTimelineViewController?.canMarkBelowArticlesAsRead() ?? false
}
2025-11-05 11:22:10 -08:00
func canShowShareMenu() -> Bool {
guard let selectedArticles = selectedArticles else {
return false
}
return !selectedArticles.isEmpty
}
func validateToggleStarred(_ item: NSValidatedUserInterfaceItem) -> Bool {
2019-02-18 13:10:16 -08:00
let validationStatus = currentTimelineViewController?.markStarredCommandStatus() ?? .canDoNothing
let starring: Bool
let result: Bool
switch validationStatus {
case .canMark:
starring = true
result = true
case .canUnmark:
starring = false
result = true
case .canDoNothing:
starring = true
result = false
}
let commandName = starring ? NSLocalizedString("Mark as Starred", comment: "Command") : NSLocalizedString("Mark as Unstarred", comment: "Command")
if let toolbarItem = item as? NSToolbarItem {
toolbarItem.toolTip = commandName
// Text Only toolbar mode shows the label and menu form representation, so they need to track state too.
let shortName = starring ? NSLocalizedString("Star", comment: "Star") : NSLocalizedString("Unstar", comment: "Unstar")
toolbarItem.label = shortName
toolbarItem.menuFormRepresentation?.title = shortName
}
if let menuItem = item as? NSMenuItem {
menuItem.title = commandName
}
2024-11-22 20:08:26 -08:00
if let toolbarItem = item as? NSToolbarItem, let button = toolbarItem.view as? NSButton {
button.image = starring ? Assets.Images.starOpen : Assets.Images.starClosed
}
return result
}
2025-11-05 11:22:10 -08:00
2020-03-15 18:02:55 -05:00
func validateCleanUp(_ item: NSValidatedUserInterfaceItem) -> Bool {
return timelineContainerViewController?.isCleanUpAvailable ?? false
2020-03-15 18:02:55 -05:00
}
func validateToggleReadFeeds(_ item: NSValidatedUserInterfaceItem) -> Bool {
guard let menuItem = item as? NSMenuItem else { return false }
let showCommand = NSLocalizedString("Show Read Feeds", comment: "Command")
let hideCommand = NSLocalizedString("Hide Read Feeds", comment: "Command")
menuItem.title = sidebarViewController?.isReadFiltered ?? false ? showCommand : hideCommand
return true
}
func validateSortArticlesByField(_ item: NSValidatedUserInterfaceItem) -> Bool {
guard let sortParameters = timelineContainerViewController?.sortParameters, let menuItem = item as? NSMenuItem, let identifier = menuItem.identifier, let key = ArticleSortKey(rawValue: identifier.rawValue) else {
2026-09-18 21:47:51 -07:00
return false
}
menuItem.state = sortParameters.key == key ? .on : .off
2026-09-18 21:47:51 -07:00
return true
}
/// The direction items are worded for the current field: Oldest/Newest for date, A to Z for text, Ascending/Descending for flags.
func validateSortDirection(_ item: NSValidatedUserInterfaceItem, direction: ComparisonResult) -> Bool {
guard let sortParameters = timelineContainerViewController?.sortParameters, let menuItem = item as? NSMenuItem else {
2026-09-18 21:47:51 -07:00
return false
}
menuItem.title = sortParameters.key.localizedDirectionTitle(ascending: direction == .orderedAscending)
menuItem.state = sortParameters.direction == direction ? .on : .off
return true
2026-09-18 21:47:51 -07:00
}
func validateToggleReadArticles(_ item: NSValidatedUserInterfaceItem) -> Bool {
let showCommand = NSLocalizedString("Show Read Articles", comment: "Command")
let hideCommand = NSLocalizedString("Hide Read Articles", comment: "Command")
guard let isReadFiltered = timelineContainerViewController?.isReadFiltered else {
(item as? NSMenuItem)?.title = hideCommand
2024-11-22 20:08:26 -08:00
if let toolbarItem = item as? NSToolbarItem, let button = toolbarItem.view as? NSButton {
toolbarItem.toolTip = hideCommand
2025-11-19 10:38:18 -08:00
button.image = Assets.Images.filterInactive
}
return false
}
if isReadFiltered {
(item as? NSMenuItem)?.title = showCommand
2024-11-22 20:08:26 -08:00
if let toolbarItem = item as? NSToolbarItem, let button = toolbarItem.view as? NSButton {
toolbarItem.toolTip = showCommand
2025-11-19 10:38:18 -08:00
button.image = Assets.Images.filterActive
}
} else {
(item as? NSMenuItem)?.title = hideCommand
2024-11-22 20:08:26 -08:00
if let toolbarItem = item as? NSToolbarItem, let button = toolbarItem.view as? NSButton {
toolbarItem.toolTip = hideCommand
2025-11-19 10:38:18 -08:00
button.image = Assets.Images.filterInactive
}
}
2025-11-05 11:22:10 -08:00
return true
}
// MARK: - Misc.
func goToNextUnreadInTimeline(wrappingToTop wrapping: Bool) {
2019-02-18 13:10:16 -08:00
guard let timelineViewController = currentTimelineViewController else {
return
}
if timelineViewController.canGoToNextUnread(wrappingToTop: wrapping) {
timelineViewController.goToNextUnread(wrappingToTop: wrapping)
makeTimelineViewFirstResponder()
}
}
func makeTimelineViewFirstResponder() {
2019-02-18 13:10:16 -08:00
guard let window = window, let timelineViewController = currentTimelineViewController else {
return
}
window.makeFirstResponderUnlessDescendantIsFirstResponder(timelineViewController.tableView)
}
2017-10-18 21:53:45 -07:00
func updateWindowTitle() {
2020-11-19 16:21:51 -06:00
guard timelineSourceMode != .search else {
let localizedLabel = NSLocalizedString("Search: %@", comment: "Search")
window?.title = NSString.localizedStringWithFormat(localizedLabel as NSString, searchString ?? "") as String
2024-11-22 20:08:26 -08:00
window?.subtitle = ""
2020-11-19 16:21:51 -06:00
return
}
2025-11-05 11:22:10 -08:00
func setSubtitle(_ count: Int) {
guard AppDefaults.unreadCountDisplay == .count else {
window?.subtitle = ""
return
}
let localizedLabel = NSLocalizedString("%d unread", comment: "Unread")
let formattedLabel = NSString.localizedStringWithFormat(localizedLabel as NSString, count)
2024-11-22 20:08:26 -08:00
window?.subtitle = formattedLabel as String
}
2024-11-22 20:08:26 -08:00
guard let selectedObjects = selectedObjectsInSidebar(), selectedObjects.count > 0 else {
2025-11-03 21:32:24 -08:00
window?.title = appName
setSubtitle(AccountManager.shared.unreadCount)
return
2017-10-18 21:53:45 -07:00
}
2024-11-22 20:08:26 -08:00
guard selectedObjects.count == 1 else {
window?.title = NSLocalizedString("Multiple", comment: "Multiple")
2024-11-22 20:08:26 -08:00
let unreadCount = selectedObjects.reduce(0, { result, selectedObject in
if let unreadCountProvider = selectedObject as? UnreadCountProvider {
return result + unreadCountProvider.unreadCount
} else {
return result
}
})
setSubtitle(unreadCount)
return
}
2024-11-22 20:08:26 -08:00
if let displayNameProvider = currentFeedOrFolder as? DisplayNameProvider {
window?.title = displayNameProvider.nameForDisplay
2024-11-22 20:08:26 -08:00
if let unreadCountProvider = currentFeedOrFolder as? UnreadCountProvider {
setSubtitle(unreadCountProvider.unreadCount)
}
}
2017-10-18 21:53:45 -07:00
}
2024-11-22 20:08:26 -08:00
2019-09-21 15:03:42 -05:00
func startArticleExtractorForCurrentLink() {
2025-11-18 14:33:24 -08:00
if let link = currentLink, let extractor = ArticleExtractor(link, delegate: self) {
2019-09-21 15:03:42 -05:00
extractor.process()
articleExtractor = extractor
}
}
func restoreSplitViewState(from state: MainWindowState) {
2026-09-19 10:44:51 -07:00
if state.splitViewWidths.count == 3 {
rememberedStandardLayoutWidths = state.splitViewWidths
}
2026-09-19 10:44:51 -07:00
rememberedColumnLayoutTimelineHeight = state.columnLayoutTimelineHeight
applyRememberedGeometry()
sidebarSplitViewItem?.isCollapsed = state.isSidebarHidden
}
/// Restore main window split view using legacy state restoration data.
///
/// TODO: Delete this for NetNewsWire 7.
func restoreLegacySplitViewState(from state: [AnyHashable: Any]) {
guard let splitView = splitViewController?.splitView,
let widths = state[MainWindowController.mainWindowWidthsStateKey] as? [Int],
widths.count == 3,
let window = window else {
return
}
let windowWidth = Int(floor(window.frame.width))
let dividerThickness: Int = Int(splitView.dividerThickness)
let sidebarWidth: Int = widths[0]
let timelineWidth: Int = widths[1]
2022-01-05 00:25:20 +02:00
// Make sure the detail view has its minimum thickness, at least.
2026-09-19 10:44:51 -07:00
if windowWidth < sidebarWidth + dividerThickness + timelineWidth + dividerThickness + Self.detailViewMinimumWidth {
return
}
2026-09-19 10:44:51 -07:00
rememberedStandardLayoutWidths = widths
applyRememberedGeometry()
let isSidebarHidden = state[UserInfoKey.isSidebarHidden] as? Bool ?? false
if !(sidebarSplitViewItem?.isCollapsed ?? false) && isSidebarHidden {
sidebarSplitViewItem?.isCollapsed = true
}
}
2020-08-09 11:46:53 -05:00
func buildToolbarButton(_ itemIdentifier: NSToolbarItem.Identifier, _ title: String, _ image: NSImage, _ selector: String) -> NSToolbarItem {
2020-08-10 03:58:19 -05:00
let toolbarItem = RSToolbarItem(itemIdentifier: itemIdentifier)
toolbarItem.autovalidates = true
2025-11-05 11:22:10 -08:00
2020-08-10 03:58:19 -05:00
let button = NSButton()
button.bezelStyle = .texturedRounded
button.image = image
button.imageScaling = .scaleProportionallyDown
2020-08-10 03:58:19 -05:00
button.action = Selector((selector))
2025-11-05 11:22:10 -08:00
2020-08-10 03:58:19 -05:00
toolbarItem.view = button
toolbarItem.toolTip = title
2020-08-10 03:58:19 -05:00
toolbarItem.label = title
// A menu form representation keeps view-based items working in the toolbar's Text Only mode and overflow menu.
toolbarItem.menuFormRepresentation = NSMenuItem(title: title, action: Selector((selector)), keyEquivalent: "")
2020-08-10 03:58:19 -05:00
return toolbarItem
}
2020-08-09 11:46:53 -05:00
func buildNewSidebarItemMenu() -> NSMenu {
let menu = NSMenu()
2025-11-05 11:22:10 -08:00
2025-11-02 16:17:42 -08:00
let newFeedItem = NSMenuItem()
newFeedItem.title = NSLocalizedString("New Feed…", comment: "Command")
2025-11-06 21:03:50 -08:00
newFeedItem.action = #selector(AppDelegate.showAddFeedWindow(_:))
2025-11-02 16:17:42 -08:00
menu.addItem(newFeedItem)
2025-11-05 11:22:10 -08:00
2020-08-09 11:46:53 -05:00
let newFolderFeedItem = NSMenuItem()
newFolderFeedItem.title = NSLocalizedString("New Folder…", comment: "Command")
2025-11-06 21:03:50 -08:00
newFolderFeedItem.action = #selector(AppDelegate.showAddFolderWindow(_:))
2020-08-09 11:46:53 -05:00
menu.addItem(newFolderFeedItem)
2025-11-05 11:22:10 -08:00
2020-08-09 11:46:53 -05:00
return menu
}
func updateArticleThemeMenu() {
guard let toolbarItem = window?.toolbar?.existingItem(withIdentifier: .articleThemeMenu) as? NSMenuToolbarItem else {
return
}
toolbarItem.menu = ArticleThemesManager.shared.makeArticleThemeMenu()
}
// MARK: - Status Bar
2025-11-05 11:22:10 -08:00
/// The status bar, when showing, takes the place of the detail view’s floating link overlay and the sidebar’s progress view.
func updateStatusBarVisibility() {
let showStatusBar = AppDefaults.showStatusBar
mainWindowContentViewController.isStatusBarHidden = !showStatusBar
detailViewController?.showsMouseoverLinkOverlay = !showStatusBar
sidebarViewController?.showsProgressView = !showStatusBar
}
func updateStatusBarLink() {
mainWindowContentViewController.statusBarView.link = mouseoverLink ?? currentLink
}
2021-09-08 19:58:40 -05:00
/// Tracks the sidebar divider in the status bar. Call after the split view controller is replaced.
func observeSplitViewForStatusBar() {
2026-10-13 15:44:27 -07:00
NotificationCenter.default.removeObserver(self, name: NSSplitView.didResizeSubviewsNotification, object: nil)
if let splitView = splitViewController?.splitView {
NotificationCenter.default.addObserver(self, selector: #selector(handleSplitViewDidResizeSubviews(_:)), name: NSSplitView.didResizeSubviewsNotification, object: splitView)
}
updateStatusBarSidebarDivider()
}
2021-09-08 19:58:40 -05:00
@objc func handleSplitViewDidResizeSubviews(_ notification: Notification) {
updateStatusBarSidebarDivider()
}
func updateStatusBarSidebarDivider() {
let statusBarView = mainWindowContentViewController.statusBarView
guard let sidebarSplitViewItem, !sidebarSplitViewItem.isCollapsed, let splitView = splitViewController?.splitView, let sidebarPane = splitView.arrangedSubviews.first else {
statusBarView.sidebarDividerPosition = nil
return
}
// Use the split view’s sidebar pane, not the sidebar view: while the sidebar slides in,
// the sidebar view’s position lags a step behind the pane and isn’t updated after the last resize.
let dividerPositionInStatusBar = statusBarView.convert(NSPoint(x: sidebarPane.frame.maxX, y: 0), from: splitView)
// Starting with macOS 26, the content beside the sidebar extends under it, and the divider is a hairline
// at the sidebar’s trailing edge. Before that, the divider follows the sidebar.
let arrangedSubviews = splitView.arrangedSubviews
if arrangedSubviews.count > 1 {
let contentExtendsUnderSidebar = arrangedSubviews[1].frame.minX < sidebarPane.frame.maxX
let hairline = 1 / (window?.backingScaleFactor ?? 1)
statusBarView.sidebarDividerLineOffset = contentExtendsUnderSidebar ? -hairline : 0
statusBarView.sidebarDividerLineWidth = contentExtendsUnderSidebar ? hairline : splitView.dividerThickness
}
statusBarView.sidebarDividerPosition = dividerPositionInStatusBar.x
2021-09-08 19:58:40 -05:00
}
2017-05-27 10:43:27 -07:00
}