Convert Error Log to .xib. De-dupe some common code.

This commit is contained in:
Brent Simmons committed 2026-06-06 13:12:32 -07:00
1 parent 62ea1f32d3
commit 35267d7d30
7 files changed
+333 -291

No files matched your search

@@ -8,6 +8,7 @@
import AppKit
import Account
import ActivityLog
import RSCore
final class ActivityLogWindowController: NSWindowController, NSWindowDelegate {
@@ -18,7 +19,7 @@ final class ActivityLogWindowController: NSWindowController, NSWindowDelegate {
UserDefaults.standard.bool(forKey: windowIsOpenKey)
}
set {
UserDefaults.standard.set(newValue, forKey: Self.windowIsOpenKey)
UserDefaults.standard.set(newValue, forKey: windowIsOpenKey)
}
}
@@ -32,8 +33,6 @@ final class ActivityLogWindowController: NSWindowController, NSWindowDelegate {
private static let maxTextEntries = 1000
private static let aboveCenterOffset: CGFloat = 40
convenience init() {
self.init(windowNibName: "ActivityLogWindow")
}
@@ -42,8 +41,8 @@ final class ActivityLogWindowController: NSWindowController, NSWindowDelegate {
super.windowDidLoad()
window?.delegate = self
textView?.font = NSFont.monospacedSystemFont(ofSize: Self.fontSize, weight: .regular)
textView?.textContainerInset = NSSize(width: Self.textContainerInset, height: Self.textContainerInset)
textView?.font = NSFont.monospacedSystemFont(ofSize: LogTextStyle.fontSize, weight: .regular)
textView?.textContainerInset = NSSize(width: LogTextStyle.textContainerInset, height: LogTextStyle.textContainerInset)
updateCopyButtonState()
@@ -55,11 +54,7 @@ final class ActivityLogWindowController: NSWindowController, NSWindowDelegate {
override func showWindow(_ sender: Any?) {
if !hasBeenShown {
hasBeenShown = true
window?.center()
if var frame = window?.frame {
frame.origin.y += Self.aboveCenterOffset
window?.setFrame(frame, display: false)
}
window?.centerAboveCenter(by: LogTextStyle.aboveCenterOffset)
}
super.showWindow(sender)
reloadEntries()
@@ -72,11 +67,7 @@ final class ActivityLogWindowController: NSWindowController, NSWindowDelegate {
// MARK: - NSWindowDelegate
func windowDidResize(_ notification: Notification) {
guard let textView, let container = textView.textContainer else {
return
}
container.size = NSSize(width: textView.bounds.width - textView.textContainerInset.width * 2, height: CGFloat.greatestFiniteMagnitude)
textView.layoutManager?.ensureLayout(for: container)
textView?.updateContainerSizeForLiveResize()
}
// MARK: - Notifications
@@ -99,11 +90,7 @@ final class ActivityLogWindowController: NSWindowController, NSWindowDelegate {
// MARK: - Actions
@IBAction func copyContents(_ sender: Any?) {
guard let text = textView?.string, !text.isEmpty else {
return
}
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
textView?.copyAllToPasteboard()
}
}
@@ -111,24 +98,6 @@ final class ActivityLogWindowController: NSWindowController, NSWindowDelegate {
private extension ActivityLogWindowController {
static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
static let fontSize: CGFloat = 16.0
static let textContainerInset: CGFloat = 8
static let lineSpacing: CGFloat = 4
static let paragraphSpacing: CGFloat = 7
static let entryParagraphStyle: NSParagraphStyle = {
let style = NSMutableParagraphStyle()
style.lineSpacing = lineSpacing
style.paragraphSpacing = paragraphSpacing
return style
}()
func rebuildIfNeeded() {
guard needsRebuild else {
return
@@ -164,7 +133,7 @@ private extension ActivityLogWindowController {
needsRebuild = true
}
let wasScrolledToBottom = isScrolledToBottom
let wasScrolledToBottom = textView.isScrolledToBottom
var didAppend = false
for activity in ActivityLog.shared.completedActivities {
@@ -189,23 +158,13 @@ private extension ActivityLogWindowController {
copyButton?.isEnabled = !(textView?.string.isEmpty ?? true)
}
var isScrolledToBottom: Bool {
guard let textView, let scrollView = textView.enclosingScrollView else {
return true
}
let contentView = scrollView.contentView
let visibleMaxY = contentView.bounds.maxY
let documentMaxY = textView.frame.maxY
return visibleMaxY >= documentMaxY - 1
}
// MARK: - Attributed Strings
func completionAttributedString(for activity: Activity) -> NSAttributedString {
let result = NSMutableAttributedString()
let date = activity.endDate ?? Date()
appendText("[\(Self.dateFormatter.string(from: date))] ", color: .secondaryLabelColor, to: result)
appendText("[\(DateFormatter.logTimestamp.string(from: date))] ", color: .secondaryLabelColor, to: result)
let isFailed = activity.state == .failed
let indicator = isFailed ? "✗ " : "✓ "
@@ -240,8 +199,8 @@ private extension ActivityLogWindowController {
func appendText(_ string: String, color: NSColor = .labelColor, weight: NSFont.Weight = .regular, to result: NSMutableAttributedString) {
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: color,
.font: NSFont.monospacedSystemFont(ofSize: Self.fontSize, weight: weight),
.paragraphStyle: Self.entryParagraphStyle
.font: NSFont.monospacedSystemFont(ofSize: LogTextStyle.fontSize, weight: weight),
.paragraphStyle: LogTextStyle.entryParagraphStyle
]
result.append(NSAttributedString(string: string, attributes: attributes))
}
+107
View File
@@ -0,0 +1,107 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="24765" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="24765"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="ErrorLogWindowController" customModule="NetNewsWire" customModuleProvider="target">
<connections>
<outlet property="copyButton" destination="TeH-NA-QRq" id="o8C-q3-FO7"/>
<outlet property="textView" destination="OtL-Sx-OU0" id="bff-Xp-YUM"/>
<outlet property="window" destination="QvC-M9-y7g" id="aLw-Wn-out"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<window title="Error Log" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" frameAutosaveName="ErrorLogWindow" animationBehavior="default" id="QvC-M9-y7g">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="196" y="240" width="640" height="400"/>
<rect key="screenRect" x="0.0" y="0.0" width="2560" height="1410"/>
<value key="minSize" type="size" width="640" height="300"/>
<view key="contentView" wantsLayer="YES" id="EiT-Mj-1SZ">
<rect key="frame" x="0.0" y="0.0" width="768" height="400"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<scrollView borderType="none" autohidesScrollers="YES" horizontalLineScroll="10" horizontalPageScroll="10" verticalLineScroll="10" verticalPageScroll="10" hasHorizontalScroller="NO" translatesAutoresizingMaskIntoConstraints="NO" id="kJF-uq-4TQ">
<rect key="frame" x="0.0" y="69" width="768" height="331"/>
<clipView key="contentView" id="Ypo-Qv-ix4">
<rect key="frame" x="0.0" y="0.0" width="768" height="331"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<textView wantsLayer="YES" editable="NO" importsGraphics="NO" richText="NO" verticallyResizable="YES" incrementalSearchingEnabled="YES" spellingCorrection="YES" smartInsertDelete="YES" id="OtL-Sx-OU0">
<rect key="frame" x="0.0" y="0.0" width="768" height="331"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
<size key="minSize" width="768" height="331"/>
<size key="maxSize" width="768" height="10000000"/>
</textView>
</subviews>
</clipView>
<constraints>
<constraint firstAttribute="width" relation="greaterThanOrEqual" constant="768" id="i3T-Hz-zYO"/>
<constraint firstAttribute="height" relation="greaterThanOrEqual" constant="256" id="xYp-MP-yQU"/>
</constraints>
<scroller key="horizontalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" horizontal="YES" id="6eX-un-x8T">
<rect key="frame" x="-100" y="-100" width="240" height="17"/>
<autoresizingMask key="autoresizingMask"/>
</scroller>
<scroller key="verticalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" horizontal="NO" id="pRJ-De-3rI">
<rect key="frame" x="751" y="0.0" width="17" height="256"/>
<autoresizingMask key="autoresizingMask"/>
</scroller>
</scrollView>
<visualEffectView blendingMode="withinWindow" material="titlebar" state="followsWindowActiveState" translatesAutoresizingMaskIntoConstraints="NO" id="U19-VM-vwr">
<rect key="frame" x="0.0" y="0.0" width="768" height="69"/>
<subviews>
<box verticalHuggingPriority="750" boxType="separator" translatesAutoresizingMaskIntoConstraints="NO" id="Kf8-Md-KPZ">
<rect key="frame" x="0.0" y="66" width="768" height="5"/>
</box>
<textField wantsLayer="YES" focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="te9-50-gJu">
<rect key="frame" x="18" y="26" width="546" height="16"/>
<textFieldCell key="cell" title="Errors may contain feed URLs and other information you may not want to share publicly." id="lKl-03-8bv">
<font key="font" usesAppearanceFont="YES"/>
<color key="textColor" name="secondaryLabelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="TeH-NA-QRq">
<rect key="frame" x="630" y="20" width="118" height="28"/>
<buttonCell key="cell" type="push" title="Copy Contents" bezelStyle="rounded" alignment="center" controlSize="large" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="k75-bg-mhK">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
</buttonCell>
<connections>
<action selector="copyContents:" target="-2" id="Zw7-Db-af2"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstItem="Kf8-Md-KPZ" firstAttribute="leading" secondItem="U19-VM-vwr" secondAttribute="leading" id="QyU-Q1-Wp9"/>
<constraint firstItem="te9-50-gJu" firstAttribute="leading" secondItem="U19-VM-vwr" secondAttribute="leading" constant="20" symbolic="YES" id="RFM-aV-AaM"/>
<constraint firstAttribute="trailing" secondItem="Kf8-Md-KPZ" secondAttribute="trailing" id="Szn-da-iY2"/>
<constraint firstAttribute="bottom" secondItem="TeH-NA-QRq" secondAttribute="bottom" constant="20" symbolic="YES" id="Uxn-0p-YPX"/>
<constraint firstItem="Kf8-Md-KPZ" firstAttribute="top" secondItem="U19-VM-vwr" secondAttribute="top" id="dVT-fU-zJI"/>
<constraint firstItem="TeH-NA-QRq" firstAttribute="firstBaseline" secondItem="te9-50-gJu" secondAttribute="firstBaseline" id="i9n-ax-BCp"/>
<constraint firstItem="TeH-NA-QRq" firstAttribute="leading" relation="greaterThanOrEqual" secondItem="te9-50-gJu" secondAttribute="trailing" constant="8" symbolic="YES" id="jCG-W2-tLx"/>
<constraint firstAttribute="trailing" secondItem="TeH-NA-QRq" secondAttribute="trailing" constant="20" symbolic="YES" id="u5X-Bh-ELF"/>
<constraint firstItem="TeH-NA-QRq" firstAttribute="top" secondItem="Kf8-Md-KPZ" secondAttribute="bottom" constant="20" symbolic="YES" id="yPO-y0-lEk"/>
</constraints>
</visualEffectView>
</subviews>
<constraints>
<constraint firstItem="U19-VM-vwr" firstAttribute="top" secondItem="kJF-uq-4TQ" secondAttribute="bottom" id="ES3-Fu-XNe"/>
<constraint firstAttribute="trailing" secondItem="kJF-uq-4TQ" secondAttribute="trailing" id="ZI5-xh-GTb"/>
<constraint firstItem="U19-VM-vwr" firstAttribute="leading" secondItem="EiT-Mj-1SZ" secondAttribute="leading" id="Zfc-tO-Etl"/>
<constraint firstAttribute="trailing" secondItem="U19-VM-vwr" secondAttribute="trailing" id="aVN-xe-Qft"/>
<constraint firstAttribute="bottom" secondItem="U19-VM-vwr" secondAttribute="bottom" id="bEJ-hv-zAD"/>
<constraint firstItem="kJF-uq-4TQ" firstAttribute="top" secondItem="EiT-Mj-1SZ" secondAttribute="top" id="enk-H1-xIp"/>
<constraint firstItem="kJF-uq-4TQ" firstAttribute="leading" secondItem="EiT-Mj-1SZ" secondAttribute="leading" id="uCM-y7-M54"/>
</constraints>
</view>
<point key="canvasLocation" x="276.5" y="-15"/>
</window>
</objects>
</document>
+57 -216
View File
@@ -8,68 +8,58 @@
import AppKit
import Account
import ErrorLog
import RSCore
@MainActor final class ErrorLogWindowController: NSWindowController, NSWindowDelegate {
final class ErrorLogWindowController: NSWindowController, NSWindowDelegate {
private static let windowIsOpenKey = "ErrorLogWindowIsOpen"
private static let errorLogWindowAutosaveFrameName = "ErrorLogWindow"
static private(set) var shouldOpenAtStartup: Bool {
get {
UserDefaults.standard.bool(forKey: windowIsOpenKey)
}
set {
UserDefaults.standard.set(newValue, forKey: Self.windowIsOpenKey)
UserDefaults.standard.set(newValue, forKey: windowIsOpenKey)
}
}
private var textView = NSTextView()
private var copyButton: NSButton?
@IBOutlet private var textView: NSTextView?
@IBOutlet private var copyButton: NSButton?
private var hasBeenShown = false
private var hasLoadedEntries = false
private var isLoadingEntries = false
private static let defaultWindowSize = NSSize(width: 640, height: 400)
private static let minimumWindowSize = NSSize(width: 640, height: 300)
private static let aboveCenterOffset: CGFloat = 40
init() {
let window = NSWindow(contentRect: NSRect(origin: .zero, size: Self.defaultWindowSize), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: true)
window.title = NSLocalizedString("Error Log", comment: "Error Log window title")
window.minSize = Self.minimumWindowSize
window.isReleasedWhenClosed = false
super.init(window: window)
setupUI()
NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidEncounterError(_:)), name: .appDidEncounterError, object: nil)
window.delegate = self
convenience init() {
self.init(windowNibName: "ErrorLogWindow")
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) is not supported")
override func windowDidLoad() {
super.windowDidLoad()
window?.delegate = self
textView?.usesFindBar = true
textView?.font = NSFont.monospacedSystemFont(ofSize: LogTextStyle.fontSize, weight: .regular)
textView?.textContainerInset = NSSize(width: LogTextStyle.textContainerInset, height: LogTextStyle.textContainerInset)
updateCopyButtonState()
NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidEncounterError(_:)), name: .appDidEncounterError, object: nil)
}
override func showWindow(_ sender: Any?) {
if !hasBeenShown {
hasBeenShown = true
window?.center()
if var frame = window?.frame {
frame.origin.y += Self.aboveCenterOffset
window?.setFrame(frame, display: false)
}
window?.setFrameAutosaveName(Self.errorLogWindowAutosaveFrameName)
window?.centerAboveCenter(by: LogTextStyle.aboveCenterOffset)
}
super.showWindow(sender)
if !hasLoadedEntries {
hasLoadedEntries = true
if !hasLoadedEntries && !isLoadingEntries {
loadEntries()
}
}
@IBAction override func performTextFinderAction(_ sender: Any?) {
textView.performTextFinderAction(sender)
textView?.performTextFinderAction(sender)
}
func saveState() {
@@ -79,149 +69,45 @@ import ErrorLog
// MARK: - NSWindowDelegate
func windowDidResize(_ notification: Notification) {
// Make the NSTextView resize during live resize.
guard let container = textView.textContainer else {
return
}
container.size = NSSize(width: textView.bounds.width - textView.textContainerInset.width * 2, height: CGFloat.greatestFiniteMagnitude)
textView.layoutManager?.ensureLayout(for: container)
textView?.updateContainerSizeForLiveResize()
}
// MARK: - Notifications
@objc func handleAppDidEncounterError(_ notification: Notification) {
guard let errorMessage = notification.userInfo?[ErrorLogUserInfoKey.errorMessage] as? String,
let sourceName = notification.userInfo?[ErrorLogUserInfoKey.sourceName] as? String,
let sourceID = notification.userInfo?[ErrorLogUserInfoKey.sourceID] as? Int else {
guard let entry = ErrorLogEntry(notification: notification) else {
return
}
let operation = notification.userInfo?[ErrorLogUserInfoKey.operation] as? String ?? ""
let fileName = notification.userInfo?[ErrorLogUserInfoKey.fileName] as? String ?? ""
let functionName = notification.userInfo?[ErrorLogUserInfoKey.functionName] as? String ?? ""
let lineNumber = notification.userInfo?[ErrorLogUserInfoKey.lineNumber] as? Int ?? 0
let entry = ErrorLogEntry(id: 0, date: Date(), sourceName: sourceName, sourceID: sourceID, operation: operation, fileName: fileName, functionName: functionName, lineNumber: lineNumber, errorMessage: errorMessage)
Task { @MainActor in
appendEntry(entry)
}
}
// MARK: - Actions
@IBAction func copyContents(_ sender: Any?) {
textView?.copyAllToPasteboard()
}
}
// MARK: - Private
private extension ErrorLogWindowController {
static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
static let fontSize: CGFloat = 16.0
static let textContainerInset: CGFloat = 8
static let separatorHeight: CGFloat = 1
static let separatorWhite: CGFloat = 0.75
static let bottomBarHeight: CGFloat = 52
static let bottomBarPadding: CGFloat = 16
static let lineSpacing: CGFloat = 4
static let paragraphSpacing: CGFloat = 7
static let entryParagraphStyle: NSParagraphStyle = {
let style = NSMutableParagraphStyle()
style.lineSpacing = lineSpacing
style.paragraphSpacing = paragraphSpacing
return style
}()
func setupUI() {
guard let contentView = window?.contentView else {
return
}
let scrollView = NSTextView.scrollableTextView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.hasVerticalScroller = true
scrollView.autohidesScrollers = true
scrollView.drawsBackground = true
let embeddedTextView = scrollView.documentView as! NSTextView
embeddedTextView.isEditable = false
embeddedTextView.isSelectable = true
embeddedTextView.usesFindBar = true
embeddedTextView.isIncrementalSearchingEnabled = true
embeddedTextView.textContainerInset = NSSize(width: Self.textContainerInset, height: Self.textContainerInset)
embeddedTextView.font = NSFont.monospacedSystemFont(ofSize: Self.fontSize, weight: .regular)
self.textView = embeddedTextView
let separator = NSView()
separator.translatesAutoresizingMaskIntoConstraints = false
separator.wantsLayer = true
separator.layer?.backgroundColor = NSColor(white: Self.separatorWhite, alpha: 1.0).cgColor
let bottomBar = NSVisualEffectView()
bottomBar.translatesAutoresizingMaskIntoConstraints = false
bottomBar.blendingMode = .withinWindow
bottomBar.material = .titlebar
let warningLabel = NSTextField(wrappingLabelWithString: NSLocalizedString("Errors may contain feed URLs and other information you may not want to share publicly.", comment: "Error log privacy warning"))
warningLabel.translatesAutoresizingMaskIntoConstraints = false
warningLabel.font = NSFont.systemFont(ofSize: Self.fontSize)
warningLabel.textColor = .secondaryLabelColor
let copyButton = NSButton(title: NSLocalizedString("Copy Contents", comment: "Copy Contents button"), target: self, action: #selector(copyContents(_:)))
copyButton.translatesAutoresizingMaskIntoConstraints = false
copyButton.controlSize = .large
copyButton.font = NSFont.systemFont(ofSize: NSFont.systemFontSize)
copyButton.isEnabled = false
self.copyButton = copyButton
bottomBar.addSubview(warningLabel)
bottomBar.addSubview(copyButton)
warningLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
copyButton.setContentCompressionResistancePriority(.required, for: .horizontal)
copyButton.setContentHuggingPriority(.required, for: .horizontal)
contentView.addSubview(scrollView)
contentView.addSubview(separator)
contentView.addSubview(bottomBar)
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: contentView.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: separator.topAnchor),
separator.heightAnchor.constraint(equalToConstant: Self.separatorHeight),
separator.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
separator.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
separator.bottomAnchor.constraint(equalTo: bottomBar.topAnchor),
warningLabel.leadingAnchor.constraint(equalTo: bottomBar.leadingAnchor, constant: Self.bottomBarPadding),
warningLabel.centerYAnchor.constraint(equalTo: bottomBar.centerYAnchor),
warningLabel.trailingAnchor.constraint(lessThanOrEqualTo: copyButton.leadingAnchor, constant: -Self.bottomBarPadding),
copyButton.trailingAnchor.constraint(equalTo: bottomBar.trailingAnchor, constant: -Self.bottomBarPadding),
copyButton.centerYAnchor.constraint(equalTo: bottomBar.centerYAnchor),
bottomBar.heightAnchor.constraint(equalToConstant: Self.bottomBarHeight),
bottomBar.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
bottomBar.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
bottomBar.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
/// Load recent entries from the on-disk error log database.
/// Load recent entries from the on-disk error log database. Notifications that arrive while
/// the load is in flight are dropped — they're already persisted by ErrorLogDatabase and will
/// be loaded the next time this window opens.
func loadEntries() {
isLoadingEntries = true
Task {
let entries = await AccountManager.shared.errorLogDatabase.allEntries()
guard !entries.isEmpty else {
defer {
isLoadingEntries = false
hasLoadedEntries = true
}
guard let textView else {
return
}
// Build attributed string for all entries at once,
// replacing any entries that arrived via notifications before the window opened.
let combined = NSMutableAttributedString()
for entry in entries {
combined.append(attributedString(for: entry))
@@ -233,13 +119,15 @@ private extension ErrorLogWindowController {
}
func appendEntry(_ entry: ErrorLogEntry) {
guard let textStorage = textView.textStorage else {
guard hasLoadedEntries else {
return
}
guard let textView, let textStorage = textView.textStorage else {
return
}
let wasScrolledToBottom = isScrolledToBottom
let attributedEntry = attributedString(for: entry)
textStorage.append(attributedEntry)
let wasScrolledToBottom = textView.isScrolledToBottom
textStorage.append(attributedString(for: entry))
if wasScrolledToBottom {
textView.scrollToEndOfDocument(nil)
@@ -248,28 +136,17 @@ private extension ErrorLogWindowController {
}
func updateCopyButtonState() {
copyButton?.isEnabled = !textView.string.isEmpty
}
var isScrolledToBottom: Bool {
guard let scrollView = textView.enclosingScrollView else {
return true
}
let contentView = scrollView.contentView
let visibleMaxY = contentView.bounds.maxY
let documentMaxY = textView.frame.maxY
// Allow 1 point of tolerance for fractional pixel rounding.
return visibleMaxY >= documentMaxY - 1
copyButton?.isEnabled = !(textView?.string.isEmpty ?? true)
}
func attributedString(for entry: ErrorLogEntry) -> NSAttributedString {
let result = NSMutableAttributedString()
let timestampString = "[\(Self.dateFormatter.string(from: entry.date))] "
let timestampString = "[\(DateFormatter.logTimestamp.string(from: entry.date))] "
let timestampAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: NSColor.secondaryLabelColor,
.font: NSFont.monospacedSystemFont(ofSize: Self.fontSize, weight: .regular),
.paragraphStyle: Self.entryParagraphStyle
.font: NSFont.monospacedSystemFont(ofSize: LogTextStyle.fontSize, weight: .regular),
.paragraphStyle: LogTextStyle.entryParagraphStyle
]
result.append(NSAttributedString(string: timestampString, attributes: timestampAttributes))
@@ -279,18 +156,18 @@ private extension ErrorLogWindowController {
} else {
sourceNameString = "\(entry.sourceName) — \(entry.operation): "
}
let sourceColor = color(for: entry.sourceID)
let sourceColor = AccountType(rawValue: entry.sourceID)?.logColor ?? .secondaryLabelColor
let sourceAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: sourceColor,
.font: NSFont.monospacedSystemFont(ofSize: Self.fontSize, weight: .medium),
.paragraphStyle: Self.entryParagraphStyle
.font: NSFont.monospacedSystemFont(ofSize: LogTextStyle.fontSize, weight: .medium),
.paragraphStyle: LogTextStyle.entryParagraphStyle
]
result.append(NSAttributedString(string: sourceNameString, attributes: sourceAttributes))
let messageAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: NSColor.labelColor,
.font: NSFont.monospacedSystemFont(ofSize: Self.fontSize, weight: .regular),
.paragraphStyle: Self.entryParagraphStyle
.font: NSFont.monospacedSystemFont(ofSize: LogTextStyle.fontSize, weight: .regular),
.paragraphStyle: LogTextStyle.entryParagraphStyle
]
result.append(NSAttributedString(string: entry.errorMessage, attributes: messageAttributes))
@@ -298,8 +175,8 @@ private extension ErrorLogWindowController {
let locationString = " (\(entry.fileName):\(entry.functionName):\(entry.lineNumber))"
let locationAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: NSColor.tertiaryLabelColor,
.font: NSFont.monospacedSystemFont(ofSize: Self.fontSize, weight: .regular),
.paragraphStyle: Self.entryParagraphStyle
.font: NSFont.monospacedSystemFont(ofSize: LogTextStyle.fontSize, weight: .regular),
.paragraphStyle: LogTextStyle.entryParagraphStyle
]
result.append(NSAttributedString(string: locationString, attributes: locationAttributes))
}
@@ -308,40 +185,4 @@ private extension ErrorLogWindowController {
return result
}
func color(for sourceID: Int) -> NSColor {
guard let type = AccountType(rawValue: sourceID) else {
return .secondaryLabelColor
}
switch type {
case .onMyMac:
return .secondaryLabelColor
case .cloudKit:
return .systemPurple
case .feedly:
return .systemGreen
case .feedbin:
return .systemBlue
case .newsBlur:
return .systemOrange
case .freshRSS:
return .systemTeal
case .inoreader:
return .systemBrown
case .bazQux:
return .systemIndigo
case .theOldReader:
return .systemPink
}
}
@objc func copyContents(_ sender: Any?) {
let text = textView.string
guard !text.isEmpty else {
return
}
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
}
}
@@ -0,0 +1,60 @@
{
"sourceLanguage" : "en",
"strings" : {
"k75-bg-mhK.title" : {
"comment" : "Class = \"NSButtonCell\"; title = \"Copy Contents\"; ObjectID = \"k75-bg-mhK\";",
"extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "new",
"value" : "Copy Contents"
}
},
"es" : {
"stringUnit" : {
"state" : "translated",
"value" : "Copiar contenido"
}
}
}
},
"lKl-03-8bv.title" : {
"comment" : "Class = \"NSTextFieldCell\"; title = \"Errors may contain feed URLs and other information you may not want to share publicly.\"; ObjectID = \"lKl-03-8bv\";",
"extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "new",
"value" : "Errors may contain feed URLs and other information you may not want to share publicly."
}
},
"es" : {
"stringUnit" : {
"state" : "translated",
"value" : "Los errores pueden contener URL de fuentes y otra información que quizás no quieras compartir públicamente."
}
}
}
},
"QvC-M9-y7g.title" : {
"comment" : "Class = \"NSWindow\"; title = \"Error Log\"; ObjectID = \"QvC-M9-y7g\";",
"extractionState" : "extracted_with_value",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "new",
"value" : "Error Log"
}
},
"es" : {
"stringUnit" : {
"state" : "translated",
"value" : "Registro de errores"
}
}
}
}
},
"version" : "1.2"
}
+69
View File
@@ -0,0 +1,69 @@
//
// LogTextStyle.swift
// NetNewsWire
//
// Created by Brent Simmons on 6/6/26.
//
import AppKit
/// Shared sizing and paragraph styling for log windows (Activity Log, Error Log) — both render a
/// stream of color-coded monospaced entries in a scrollable NSTextView with a Copy Contents bar
/// across the bottom.
enum LogTextStyle {
static let fontSize: CGFloat = 16.0
static let textContainerInset: CGFloat = 8
/// Vertical nudge above the centered position used when first opening a log window.
static let aboveCenterOffset: CGFloat = 40
@MainActor static let entryParagraphStyle: NSParagraphStyle = {
let style = NSMutableParagraphStyle()
style.lineSpacing = 4
style.paragraphSpacing = 7
return style
}()
}
extension NSTextView {
/// True when the visible region reaches the bottom of the document (1pt tolerance).
var isScrolledToBottom: Bool {
guard let scrollView = enclosingScrollView else {
return true
}
let visibleMaxY = scrollView.contentView.bounds.maxY
let documentMaxY = frame.maxY
return visibleMaxY >= documentMaxY - 1
}
/// Re-flow the text container to the current width during live resize.
func updateContainerSizeForLiveResize() {
guard let container = textContainer else {
return
}
container.size = NSSize(width: bounds.width - textContainerInset.width * 2, height: .greatestFiniteMagnitude)
layoutManager?.ensureLayout(for: container)
}
/// Copy the full text to the general pasteboard. No-op when empty.
func copyAllToPasteboard() {
guard !string.isEmpty else {
return
}
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(string, forType: .string)
}
}
extension NSWindow {
/// Center the window, then nudge above center by the given offset. Used on the first show
/// of log windows.
func centerAboveCenter(by offset: CGFloat) {
center()
var newFrame = frame
newFrame.origin.y += offset
setFrame(newFrame, display: false)
}
}
@@ -36,3 +36,28 @@ public struct ErrorLogUserInfoKey {
]
}
}
public extension ErrorLogEntry {
/// Build an entry from an `.appDidEncounterError` notification. Returns nil if any required
/// key is missing. The id is 0 — the entry has not yet been persisted.
init?(notification: Notification) {
guard let userInfo = notification.userInfo,
let errorMessage = userInfo[ErrorLogUserInfoKey.errorMessage] as? String,
let sourceName = userInfo[ErrorLogUserInfoKey.sourceName] as? String,
let sourceID = userInfo[ErrorLogUserInfoKey.sourceID] as? Int else {
return nil
}
self.init(
id: 0,
date: Date(),
sourceName: sourceName,
sourceID: sourceID,
operation: userInfo[ErrorLogUserInfoKey.operation] as? String ?? "",
fileName: userInfo[ErrorLogUserInfoKey.fileName] as? String ?? "",
functionName: userInfo[ErrorLogUserInfoKey.functionName] as? String ?? "",
lineNumber: userInfo[ErrorLogUserInfoKey.lineNumber] as? Int ?? 0,
errorMessage: errorMessage
)
}
}
+4 -23
View File
@@ -8,6 +8,7 @@
import SwiftUI
import Account
import ErrorLog
import RSCore
struct ErrorLogView: View {
@@ -49,7 +50,7 @@ struct ErrorLogView: View {
plainText = buildPlainText(entries)
}
.onReceive(NotificationCenter.default.publisher(for: .appDidEncounterError)) { notification in
guard let entry = errorLogEntry(from: notification) else {
guard let entry = ErrorLogEntry(notification: notification) else {
return
}
entries.append(entry)
@@ -72,12 +73,6 @@ struct ErrorLogView: View {
private extension ErrorLogView {
static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
func buildAttributedString(_ entries: [ErrorLogEntry]) -> AttributedString {
var result = AttributedString()
for entry in entries {
@@ -87,7 +82,7 @@ private extension ErrorLogView {
}
func attributedString(for entry: ErrorLogEntry) -> AttributedString {
var timestamp = AttributedString("[\(Self.dateFormatter.string(from: entry.date))] ")
var timestamp = AttributedString("[\(DateFormatter.logTimestamp.string(from: entry.date))] ")
timestamp.foregroundColor = .secondary
let sourceString: String
@@ -120,7 +115,7 @@ private extension ErrorLogView {
func buildPlainText(_ entries: [ErrorLogEntry]) -> String {
var result = ""
for entry in entries {
result += "[\(Self.dateFormatter.string(from: entry.date))] "
result += "[\(DateFormatter.logTimestamp.string(from: entry.date))] "
if entry.operation.isEmpty {
result += "\(entry.sourceName): "
} else {
@@ -134,18 +129,4 @@ private extension ErrorLogView {
}
return result
}
func errorLogEntry(from notification: Notification) -> ErrorLogEntry? {
guard let errorMessage = notification.userInfo?[ErrorLogUserInfoKey.errorMessage] as? String,
let sourceName = notification.userInfo?[ErrorLogUserInfoKey.sourceName] as? String,
let sourceID = notification.userInfo?[ErrorLogUserInfoKey.sourceID] as? Int else {
return nil
}
let operation = notification.userInfo?[ErrorLogUserInfoKey.operation] as? String ?? ""
let fileName = notification.userInfo?[ErrorLogUserInfoKey.fileName] as? String ?? ""
let functionName = notification.userInfo?[ErrorLogUserInfoKey.functionName] as? String ?? ""
let lineNumber = notification.userInfo?[ErrorLogUserInfoKey.lineNumber] as? Int ?? 0
return ErrorLogEntry(id: 0, date: Date(), sourceName: sourceName, sourceID: sourceID, operation: operation, fileName: fileName, functionName: functionName, lineNumber: lineNumber, errorMessage: errorMessage)
}
}